Because I met a problem before:
Write a Java application that uses the Randomaccessfile class to write several int integers (1,2,3,4,5,6,7,8,9,10) to a Tom.dat file and then read the data in reverse order and display it on the screen. (Note that an int type data occupies 4 bytes)
The problem requires the reverse output of the file, the first idea is to use Randomaccessfile to write to the file, and then start using the read to store the read data into the array, and finally to traverse the output backwards. After the writing, feel very not right, because the topic of the attention of the condition is not used !
So I saw a piece of code on the Web:
public static void Main (string[] args) {
try {
File File=new file ("Tom.dat");
Randomaccessfile rafile=new randomaccessfile (file, "RW");
for (int i=1;i<=10;i++)
Rafile.writeint (i);
Set the file pointer position and move the pointer forward each time you read one
for (int i=40-4;i>=0;i-=4)
{
Rafile.seek (i);
int A=rafile.readint ();
System.out.println (a);
}
catch (Exception e) {
}}
Because an int is 4 bytes, so here we first move the pointer to the Nineth bit, that is, the 36th bit, then the output, each output one, let the pointer move forward four positions, this method is a good solution to the problem.
Another is to find a wrong point, in the use of randomaccessfile to read and write operations, if it is from the first position to read, then it is important to note that the completion of the write operation, the file pointer to 0 before the read operation.