Randomaccessfile Implement the contents of the reverse output file

Source: Internet
Author: User

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.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.