Java,需要一个while循环才能达到eof.即,while !eof,继续解析 [英] Java, need a while loop to reach eof. i.e.while !eof, keep parsing
问题描述
我目前有一个可用的解析器.它解析一个文件一次(不是我想要它做的),然后将解析的数据输出到一个文件中.我需要它继续解析并附加到同一个输出文件,直到输入文件结束.看起来像这样.
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){
}
推荐答案
警告:此答案不正确.请参阅注释以获取解释.
Warning: This answer is incorrect. See the comments for explanation.
与其循环直到抛出 EOFException,您还可以采用更简洁的方法,并使用 available()
.
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.即,while !eof,继续解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!