1. Random Access Stream Randomaccessfile
The Randomaccessfile class does not belong to a stream and is a subclass of the object class. But it incorporates the functions of InputStream and OutputStream. Supports read and write to random access files.
Randomaccessfile Method of Construction:
Construction Method Summary |
RandomAccessFile(File file, String mode) Creates a random-access file stream from which to read and write (optionally), which is specified by the File parameter. |
RandomAccessFile(String name, String mode) Creates a random-access file stream from which to read and write (optionally) a file with the specified name. |
2. code example:
1 Packagecn.itcast_05;2 3 Importjava.io.IOException;4 ImportJava.io.RandomAccessFile;5 6 /*7 * Public randomaccessfile (String name,string mode): The first parameter is the file path, and the second parameter is the mode of the action file. 8 * There are four modes, our most commonly used is called "RW", this means that I can write data, can also read data9 */Ten Public classRandomaccessfiledemo { One Public Static voidMain (string[] args)throwsIOException { A //write (); - read (); - } the - Private Static voidRead ()throwsIOException { - //Create a random-access stream object -Randomaccessfile RAF =NewRandomaccessfile ("Raf.txt", "RW"); + - inti =raf.readint (); + System.out.println (i); A //The file pointer can be read by the Getfilepointer method and set through the Seek method. atSYSTEM.OUT.PRINTLN ("The pointer position of the current file is:" +Raf.getfilepointer ()); - - CharCH =Raf.readchar (); - System.out.println (CH); -SYSTEM.OUT.PRINTLN ("The pointer position of the current file is:" +Raf.getfilepointer ()); - inString s =Raf.readutf (); - System.out.println (s); toSYSTEM.OUT.PRINTLN ("The pointer position of the current file is:" +Raf.getfilepointer ()); + - //I don't want to start over, I'm going to read a, what do I do? the function of random access can be achieved by the Seek location method theRaf.seek (4); *CH =Raf.readchar (); $ System.out.println (CH);Panax Notoginseng } - the Private Static voidWrite ()throwsIOException { + //Create a random-access stream object ARandomaccessfile RAF =NewRandomaccessfile ("Raf.txt", "RW"); the + //How to play it? -Raf.writeint (100); $Raf.writechar (' a '); $RAF.WRITEUTF ("China")); - - raf.close (); the } -}
Run the effect as follows:
Java Fundamentals Hardening IO Stream Note 63: Random Access Stream Randomaccessfile