本文介绍了Java,需要一个while循环来实现eof。 ie while!eof,继续解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I currently have a working parser. It parses a file once(not what I want it to do) and then outputs parsed data into a file. I need it to keep parsing and appending to the same output file until the end of the input file. Looks something like this.

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

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

Everything is done except the while loop. It only parses once when I need it to keep parsing. I'm looking for a while loop function to reach eof.

我也在使用DataInputStream。是否存在某种DataInputStream.hasNext函数?

I'm also using a DataInputStream. Is there some sort of DataInputStream.hasNext function?

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){
}


推荐答案

而不是循环,直到抛出EOFException,你可以采取更清洁的方法,并使用。

Instead of looping until an EOFException is thrown, you could take a much cleaner approach, and use available().

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

或者,如果您选择采用EOF方法,则需要在捕获异常时设置布尔值,并在循环中使用该布尔值,但我不建议:

Alternatively, if you choose to take the EOF approach, you would want to set a boolean upon the exception being caught, and use that boolean in your loop, but I do not recommend it:

DataInputStream dis = new DataInputStream(new FileInputStream(inFile));
boolean eof = false;
while (!eof) {
    try {
        // read and use data
    } catch (EOFException e) {
        eof = true;
    }
}

这篇关于Java,需要一个while循环来实现eof。 ie while!eof,继续解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:52
查看更多