简体   繁体   English

从Java中的随机访问文件读取

[英]Reading from random access file in Java

I am trying to set up a while loop that will read from a RandomAccessFile and stop when it reaches the end of the file. 我试图建立一个while循环,该循环将从RandomAccessFile读取并在到达文件末尾时停止。 But every time I try running the program I get an error. 但是每次我尝试运行该程序时,都会出现错误。

RandomAccessFile raf = new RandomAccessFile(filename, "rw");
    final int EOF = -1;

    while(raf.readInt() != EOF){

    id = raf.readInt();
    existingMileage = raf.readInt();
    gasCost = raf.readInt();
    ndays = raf.readInt();
    rate = raf.readInt();
    totalCharge = raf.readInt();
    discount = raf.readInt();
    tax = raf.readInt();
    netCharge = raf.readInt();
    returnMileage = raf.readInt();

    }

This is the error I am getting: 这是我得到的错误:

Exception in thread "main" java.io.EOFException
at java.io.RandomAccessFile.readInt(Unknown Source)
at TakeHome.TakeHome.fileReaderMethod(TakeHome.java:127)
at TakeHome.TakeHome.main(TakeHome.java:20)
 final int EOF = -1;

You made that up. 你弥补了 It isn't in the Javadoc. 它不在Javadoc中。 The readInt() method doesn't return -1 at end of file. readInt()方法在文件末尾不返回-1。 It can't. 不可以 -1 is an in-band value. -1是带内值。 It throws the very EOFException you are getting. 它抛出您得到的非常EOFException

You're also throwing the int that you read at the EOF test away, so you're reaching end of file sooner than you should be. 您还会丢掉在EOF测试中读取的int ,因此比预期的要早到达文件结尾。

You should loop while (true) , catch EOFException , and break when you catch it. 您应该while (true)循环,捕获EOFException ,并在捕获时中断。

This is one way to handle a RandomAccessFile: 这是处理RandomAccessFile的一种方法:

RandomAccessFile file = new RandomAccessFile("testFile", "r");

//random code in between

while(true){
   try{
      //do stuff with code, like reading from file
   } catch(EOFException e){
      break;
   }
}

//do some more stuff if you like

file.close();

The file you are reading needs to be also created as a binary file. 您正在读取的文件也需要创建为二进制文件。 If you are trying to read from a file that you created as text then the reader will read 4 bytes for the int and for example if you have a sequence of numbers 12345678 the reader doesn't know that these are separate numbers and will treat it as one integer and then go to the end of file. 如果您尝试读取作为文本创建的文件,则读取器将读取int的4个字节,例如,如果您有一个数字序列12345678,则该读取器将不知道这些是单独的数字,并将对其进行处理作为一个整数,然后转到文件末尾。 Another thing to mention is that you need to catch the EOFException to end the loop cause -1 can also be an integer. 要提到的另一件事是,您需要捕获EOFException才能结束循环,因为-1也可以是整数。

Hope that helps. 希望能有所帮助。

EDIT: Try this 编辑:试试这个

RandomAccessFile raf = new RandomAccessFile(new File("/path/to/file"), "rw");
        int numberCounter = 0;
        int totalNumbers = 10;
        for (int i = 0; i < totalNumbers; i++)
        {
            raf.writeInt(i * 2);
        }

        raf.seek(0);

        try
        {
            while (true)
            {
                int id = raf.readInt();
                System.out.println(id);
                numberCounter++;

            }
        }
        catch (EOFException ex)
        {
            System.out.println("Total number " + numberCounter);
            System.out.println("End of file reached!");
        }
        finally
        {
            raf.close();
        }

Output: 输出:

0
2
4
6
8
10
12
14
16
18
Total number 10
End of file reached!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM