3

我目前有一个工作解析器。它解析一个文件一次(不是我想要的),然后将解析后的数据输出到一个文件中。我需要它继续解析并附加到同一个输出文件,直到输入文件结束。看起来像这样。

try {
// my code parsing the data and appending to eof of output. (works)
}
catch (EOFException eof){
}

除了while循环外,一切都完成了。它只在我需要它继续解析时解析一次。我正在寻找一个while循环函数来达到eof。

我也在使用 DataInputStream。是否有某种 DataInputStream.hasNext 功能?

DataInputStream dis = new DataInputStream(new FileInputStream(inFile));
i.e. dis.read();

.

//Need a while !eof while loop
try {
// my code parsing the data and appending to eof of output. (works)
}
catch (EOFException eof){
}
4

3 回答 3

7

警告:此答案不正确。请参阅评论以获取解释。


而不是循环直到抛出 EOFException,您可以采取更清洁的方法,并使用available().

DataInputStream dis = new DataInputStream(new FileInputStream(inFile));
while (dis.available() > 0) {
    // read and use data
}

或者,如果您选择采用 EOF 方法,您可能希望在捕获的异常时设置一个布尔值,并在循环中使用该布尔值,但我不建议这样做:

DataInputStream dis = new DataInputStream(new FileInputStream(inFile));
boolean eof = false;
while (!eof) {
    try {
        // read and use data
    } catch (EOFException e) {
        eof = true;
    }
}
于 2013-06-05T16:39:48.487 回答
3

DataInputStream有很多readXXX()方法可以 throwEOFException但您正在使用的方法DataInputStream.read() 不会throw EOFException

要在使用时正确识别 EOF,请按如下方式read()实现您的循环while

int read = 0;
byte[] b = new byte[1024];
while ((read = dis.read(b)) != -1) { // returns numOfBytesRead or -1 at EOF
  // parse, or write to output stream as
  dos.write(b, 0, read); // (byte[], offset, numOfBytesToWrite)
}
于 2013-06-05T16:49:06.293 回答
0

如果您正在使用FileInputStream,这里有一个类的 EOF 方法,该类有一个名为 的 FileInputStream 成员fis

public boolean isEOF() 
{ 
    try { return fis.getChannel().position() >= fis.getChannel().size()-1; } 
    catch (IOException e) { return true; } 
}
于 2017-07-10T21:18:30.383 回答