Randomaccessfile:
Characteristics:
1. Only files can be manipulated
2. Can read, have the ability to write
3. Maintains a byte array that internally defines the read and write of the byte stream
4. By manipulating the pointer, you can read and write to any location on the file.
Function: Getfilepointer seek method for manipulating file pointers.
Note: Random read and write does not mean that the data is written to any random file, but rather in the specified file through a file pointer to the file specified in the location of the read and write.
Importjava.io.FileNotFoundException;Importjava.io.IOException;ImportJava.io.RandomAccessFile; Public classRandomaccessfiledemo { Public Static voidMain (string[] args)throwsIOException {/** Randomaccessfile * Features: * 1. can only manipulate files * 2. Can read, can write * 3. Maintains a byte array that internally defines the read and write bytes Into*/ //WriteFile ();ReadFile (); } Public Static voidReadFile ()throwsIOException {randomaccessfile RAF=NewRandomaccessfile ("Tempfile\\random.txt", "R"); //Random Read, just by setting the position of the pointerRaf.seek (8); byte[] buf =New byte[4]; Raf.read (BUF); String name=NewString (BUF); intAge =Raf.readint (); SYSTEM.OUT.PRINTLN (Name+":"+Age ); Raf.close (); } Public Static voidWriteFile ()throwsIOException {//1. Create an object that accesses files randomly//The file does not exist, is created, exists, and does not create a overwriteRandomaccessfile RAF =NewRandomaccessfile ("Tempfile\\random.txt", "RW"); //2. Write name and age//raf.write ("Zhang San". GetBytes ());//raf.writeint ();//guaranteed byte integrity of integers//Raf.write ("John Doe". GetBytes ());//Raf.writeint (in);//guaranteed byte integrity of integers//3. Random WriteRaf.seek (8);//set the position of the pointer, you can modify the data inside the file at any timeRaf.write ("Harry". GetBytes ()); Raf.writeint (100); System.out.println (Raf.getfilepointer ()); //I want the data to be a bit regular when randomly accessedRaf.close (); }}
randomaccessfile--Random Access files