从Java中的随机访问文件中读取 [英] Reading from random access file in Java

查看:758
本文介绍了从Java中的随机访问文件中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置一个while循环,它将从RandomAccessFile读取并在到达文件末尾时停止。但每次我尝试运行程序时都会出错。

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. 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();

    }

这是我得到的错误:

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;

你做到了。它不在Javadoc中。 readInt()方法在文件末尾不返回-1。它不能。 -1是带内值。它会抛出你得到的 EOFException

You made that up. It isn't in the Javadoc. The readInt() method doesn't return -1 at end of file. It can't. -1 is an in-band value. It throws the very EOFException you are getting.

你还抛出 int 你在EOF测试中读到的,所以你比你应该更早到达文件的末尾。

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.

你应该循环 while(true),catch EOFException ,并在捕获时中断。

You should loop while (true), catch EOFException, and break when you catch it.

这篇关于从Java中的随机访问文件中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆