Java, need a while loop to reach eof. i.e.while !eof, keep parsing

*爱你&永不变心* 提交于 2019-12-01 08:33:22

问题


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

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.

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

回答1:


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
}

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;
    }
}



回答2:


DataInputStream has a lot of readXXX() methods that do throw EOFException but the method that you're using DataInputStream.read() does not throw EOFException.

To correctly identify the EOF while using read() implement your while loop as follows

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



回答3:


If you are using FileInputStream, here's an EOF method for a class that has a FileInputStream member called fis.

public boolean isEOF() 
{ 
    try { return fis.getChannel().position() >= fis.getChannel().size()-1; } 
    catch (IOException e) { return true; } 
}


来源:https://stackoverflow.com/questions/16945335/java-need-a-while-loop-to-reach-eof-i-e-while-eof-keep-parsing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!