1.RandomAccessFile
Randomaccessfile primarily for read and write access to file content
2. Access mode
"R": Read-only mode.
"RW": Opens for Read and access and creates a file if the file does not exist.
"RWS": Written in addition to the ' RW ' feature, file contents or metadata updates.
"RWD": In addition to the ' RW ' feature, the file content is written together when it is updated.
3. Use Cases
Packagetest;ImportJava.io.File;Importjava.io.FileNotFoundException;Importjava.io.IOException;ImportJava.io.RandomAccessFile; Public classrandomaccess { Public Static voidMain (string[] args) {Try{File File=NewFile ("C:\\img\\666.txt"); //Open FileRandomaccessfile randomaccess =NewRandomaccessfile (file, "RWD");//Accessing FilesLong lenth = Randomaccess.length ();//Get file lengthSystem.out.println ("Lenth:" +lenth); Randomaccess.seek (4);//Set pointer position//Read File intc = Randomaccess.read ();//read one byteSystem.out.println ("C:" +c); System.out.println ("C:" + (Char) c);//Convert to character byte[] B =New byte[3];//reading byte numbers, creating arraysRandomaccess.read (b, 1, 2);//read two bytes from pointer 1 write to array bString s =NewString (b);//Convert to StringSystem.out.println ("byte:" +s);//Output//Write FileFile file2 =NewFile ("C:\\img\\777.txt"); if(!File2.getparentfile (). exists ()) {File2.getparentfile (). Mkdirs (); } file2.createnewfile (); Randomaccessfile RandomAccess2=NewRandomaccessfile (File2, "RWD");//Accessing FilesRandomaccess2.write (b);//Write character Array//Close FileRandomaccess.close (); Randomaccess2.close (); } Catch(FileNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}
Java Core Programming--file Random read-write class (Randomaccessfile)