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

前端 未结 3 566
花落未央
花落未央 2021-01-14 10:45

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 s

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-14 11:23

    Warning: This answer is incorrect. See the comments for explanation.


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

提交回复
热议问题