Java provides the RandomAccessFile class to allow data to be read from and written to at any locations in the file. All of the streams you have used so far are known asread-onlyorwrite-onlystreams. These streams are calledsequential streams. A file that is opened using a sequential stream is called asequential-access file. The contents of a sequential-access file cannot be updated. However, it is often necessary to modify files. Java provides theRandomAccessFileclass to allow data to be read from and written to at any locations in a file. A file that is opened using theRandomAccessFileclass is known as arandom-access file.
TheRandomAccessFileclass implements theDataInputandDataOutputinterfaces, as shown in Figure below. TheDataInputinterface defines the methods for reading primitive-type values and strings (e.g.,readInt,readDouble,readChar,readBoolean,readUTF) and theDataOutputinterface defines the methods for writing primitive-type values and strings (e.g.,writeInt,writeDouble,writeChar,writeBoolean,writeUTF).
When creating aRandomAccessFile, you can specify one of two modes:rorrw. Modermeans that the stream is read-only, and moderwindicates that the stream allows both read and write. For example, the following statement creates a new stream,raf, that allows the program to read from and write to the filetest.dat:
RandomAccessFile raf = new RandomAccessFile("test.dat", "rw");
Iftest.datalready exists,rafis created to access it; iftest.datdoes not exist, a new file namedtest.datis created, andrafis created to access the new file. The methodraf.length()returns the number of bytes intest.datat any given time. If you append new data into the file,raf.length()increases.
If the file is not intended to be modified, open it with thermode. This prevents unintentional modification of the file.
A random-access file consists of a sequence of bytes. A special marker called afile pointeris positioned at one of these bytes. A read or write operation takes place at the location of the file pointer. When a file is opened, the file pointer is set at the beginning of the file. When you read or write data to the file, the file pointer moves forward to the next data item. For example, if you read anintvalue usingreadInt(), the JVM reads4bytes from the file pointer, and now the file pointer is4bytes ahead of the previous location, as shown in Figure below.
For aRandomAccessFile raf, you can use theraf.seek(position)method to move the file pointer to a specified position.raf.seek(0)moves it to the beginning of the file, andraf.seek(raf.length())moves it to the end of the file. The code below demonstratesRandomAccessFile.
package demo; import java.io.*; public class TestRandomAccessFile { public static void main(String[] args) throws IOException { try( // Create a random access file RandomAccessFile inout = new RandomAccessFile("inout.dat", "rw"); ) { // Clear the file to destroy the old contents if exists inout.setLength(0); // Write new integers to the file for(int i = 0; i < 200; i++) inout.writeInt(i); // Display the current length of the file System.out.println("Current file length is " + inout.length()); // Retrieve the first number inout.seek(0); // Move the file pointer to the beginning System.out.println("The first number is " + inout.readInt()); // Retrieve the second number inout.seek(1 * 4); // Move the file pointer to the second number System.out.println("The second number is " + inout.readInt()); // Retrieve the tenth number inout.seek(9 * 4); // Move the file pointer to the tenth number System.out.println("The tenth number is " + inout.readInt()); // Modify the eleventh number inout.writeInt(555); // Append a new number inout.seek(inout.length()); // Move the file pointer to the end inout.writeInt(999); // Display the new length System.out.println("The new length is " + inout.length()); // Retrieve the new eleventh number inout.seek(10 * 4); // Move the file pointer to the eleventh number System.out.println("The eleventh number is " + inout.readInt()); } } }
Current file length is 800
The first number is 0
The second number is 1
The tenth number is 9
The new length is 804
The eleventh number is 555
ARandomAccessFileis created for the file namedinout.datwith moderwto allow both read and write operations in line 8.
inout.setLength(0)sets the length to0in line 11. This, in effect, destroys the old contents of the file.
Theforloop writes200 intvalues from0to199into the file in lines 14 and 15. Since eachintvalue takes4bytes, the total length of the file returned frominout.length()is now800(line 18), as shown in the sample output.
Der Aufruf voninout.seek(0)in Zeile 21 setzt den Dateizeiger auf den Anfang der Datei.inout.readInt()liest den ersten Wert in Zeile 22 und bewegt den Dateizeiger auf die nächste Zahl. Die zweite Zahl steht in Zeile 26.
inout.seek(9 * 4)(Zeile 29) verschiebt den Dateizeiger auf die zehnte Zahl.inout.readInt()liest die zehnte Zahl und verschiebt den Dateizeiger auf die elfte Zahl in Zeile 30.inout.write(555)schreibt eine neue elfte Zahl an der aktuellen Position (Zeile 33). Die bisherige elfte Nummer wird zerstört.
inout.seek(inout.length())verschiebt den Dateizeiger an das Ende der Datei (Zeile 36).inout.writeInt(999)schreibt ein999in die Datei (Zeile 37). Jetzt wird die Länge der Datei um4erhöht, sodassinout.length()804zurückgibt (Zeile 40).
inout.seek(10 * 4)verschiebt den Dateizeiger auf die elfte Zahl in Zeile 43. Die neue elfte Zahl,555, wird in Zeile 44.
angezeigtDas obige ist der detaillierte Inhalt vonDateien mit wahlfreiem Zugriff. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!