java.io
Class Randomaccessfile
Java.lang.Object java.io.randomaccessfile
1. This class is not a subclass in an IO stream.
2. This class can be read and write.
3. The object has a byte array inside it, and the pointer can manipulate the elements in the array.
4. In fact, the object is to encapsulate the byte input stream and the output stream.
5. The object can only operate on files, and the destination and source can only be file objects. It can be seen by looking at the construction method.
randomaccessfile (file file, randomaccessfile (string name,
Seek IOException Setting the initial position of the pointer
Getfilepointer () throws IOException returns the position of the pointer, which is the offset from the beginning, in bytes.
The mode parameter specifies the access pattern to open the file:
| |
|
| "R" |
Open as read-only. Any write method that invokes the result object will cause ioexception . |
| "RW" |
open for read and write. If the file does not already exist, try to create the file. |
| "RWS" |
open for read and write, and for RW , it also requires that each update to the contents or metadata of the file be synchronously written to the underlying storage device. |
| "RWD"    |
RW , also requires that each update to the file contents be synchronously written to the underlying storage device. |
Code:
Written in Ranacc.txt, Zhang San, 97, Wang Qiang, 99
//use the Randomaccessfile object to write some information about people, such as name and age. Public Static voidWriteFile ()throwsioexception{/** If file does not exist, create if file exists, do not create **/Randomaccessfile RAF=NewRandomaccessfile ("Ranacc.txt", "RW"); Raf.write ("Zhang San". GetBytes ()); Raf.writeint (97); Raf.write (Xiaoqiang. GetBytes ()); Raf.writeint (99);// Raf.close (); }
The byte array in the randomaccessfile object is stored as shown in the following:
The kanji is two bytes and the number is one byte:
Then demand read the information of the cockroach, put the cockroach, 99 output.
This uses the Seek method in the randomaccessfile object.
/*** Read the information of the cockroach, not the Zhang San information *@throwsIOException*/ Public Static voidReadFile ()throwsIOException {randomaccessfile RAF=NewRandomaccessfile ("Ranacc.txt", "R"); //sets the position of the pointer through seek. Raf.seek (1*8);//random reads. Just specify the position of the pointer. byte[] buf =New byte[4]; Raf.read (BUF); String name=NewString (BUF);// intAge = Raf.readint ();//starts reading 4 bytes from the current pointerSystem.out.println ("Name=" +name); System.out.println ("Age=" +Age ); System.out.println ("POS:" +raf.getfilepointer ());//get the position of the pointerRaf.close (); }
Output:
Name= Xiao Qiang
age=99
Pos:16
Conclusion: Random reads can read data from any location in a byte array.