Java's RandomAccessFile provides the ability to read and write files. Unlike normal input and output streams, RamdomAccessFile can access any part of the file. This is the meaning of "Random.
The RandomAccessFile object contains a record pointer used to identify the read/write position of the current stream. This position can be moved forward or backward. RandomAccessFile contains two methods to operate the file record pointer.
Long getFilePoint (): record the current position of the file pointer.
Void seek (long pos): locates the file record pointer to the pos position.
RandomAccessFile contains three read methods of InputStream and three write methods of OutputStream. RandomAccessFile also contains a series of readXxx and writeXxx methods to complete input and output.
The construction method of RandomAccessFile is as follows:
There are four modes
"R": Open the specified file in read-only mode. If you write, there will be an IOException.
"Rw": Open the specified file in read/write mode. If the file does not exist, create a new file.
"Rws": no more.
"Rwd": not introduced either.
The following describes how to read an object from the center.
[Java]
Import java. io. RandomAccessFile;
Public class work {
Public static void main (String [] args) throws Exception {
RandomAccessFile raf = new RandomAccessFile ("work", "r ");
Raf. seek (4 );
Byte [] buffer = new byte [100];
Int len = 0;
While (len = raf. read (buffer, 0,100 ))! =-1)
{
System. out. println (new String (buffer, 0, len ));
}
}
}
Import java. io. RandomAccessFile;
Public class work {
Public static void main (String [] args) throws Exception {
RandomAccessFile raf = new RandomAccessFile ("work", "r ");
Raf. seek (4 );
Byte [] buffer = new byte [100];
Int len = 0;
While (len = raf. read (buffer, 0,100 ))! =-1)
{
System. out. println (new String (buffer, 0, len ));
}
}
}
The following content is added at the end of the file:
[Java]
Import java. io. RandomAccessFile;
Public class work {
Public static void main (String [] args) throws Exception {
RandomAccessFile raf = new RandomAccessFile ("work", "rw ");
Raf. seek (raf. length ());
Raf. write ("hello world! ". GetBytes ());
Raf. close ();
}
}
Import java. io. RandomAccessFile;
Public class work {
Public static void main (String [] args) throws Exception {
RandomAccessFile raf = new RandomAccessFile ("work", "rw ");
Raf. seek (raf. length ());
Raf. write ("hello world! ". GetBytes ());
Raf. close ();
}
}
Adding content to the file is also a good solution. First, move the pointer to the specified position, save the pointer to the temporary file, move the pointer to the specified position, add the content, and then add the class capacity of the temporary file to the back. I will not implement this. First, let's take a look at 21 episodes of the great Qin Empire. Shang Yang is very sharp in the great Qin Dynasty. The law enforcement is too strict, and roommates are watching it.