开发者

Java's PushbackReader and EOF

I am writing a parser in Java and trying to leverage Java's PushbackReader. My parser may need to backtrack if it guessed incorrectly - but once the reader reaches EOF, that fails.

Let's say I am parsing a quo开发者_如何学JAVAted String and I'm looking for the closing quotes. If any of my parser plugins can't completely finish, they try to leave the reader in the original state and pass it to the next plugin. IE: I generally push chars back onto the buffer and let the next element try to parse the buffer.

Unfortunately, if I 'read' all the way to the last character ... and then read the EOF, the PushbackReader will not allow me to push anything back onto it. Consequently, my parsing can't complete since those chars are lost!

Do I need to write my own reader for this type of string processing?

EDIT: furthermore, when I read the last character (the one just before EOF), I can't "unread" that char either. Is there a standard workaround for this - short of creating my own stack or buffer implementation?


Be careful to never unread the EOF marker, the buffer inside PushbackReader is of type char[], so the integer -1 will get converted to char 0xFFFF, which will then be the next character returned from the read method. For example when parsing a quoted String always include a check for -1 in addition to the ending quote character and handle this as a failure case, for example by throwing an IOException.


I appreciated this question and answer because it saved me time looking into a solution that wasn't suited for what I needed which was a PushbackLineReader.

I was parsing a log file and needed a block of data with pattern one and pattern two in it as shown.

TIMESTAMP pattern one
several lines with pattern two
next line <<< I need to read this line to know I'm at the end of pattern two
TIMESTAMP pattern one
several lines with pattern two
TIMESTAMP pattern one <<< I need to read this but also push it back
several lines with pattern two

So I needed to read an entire line and then when I read one line past the line that had pattern two, I need to push back the line just read.

I decided writing my own class to do that. Which given I only had one line to push back was simple enough

class MyPushbackLineReader {
    private String pushedBackLine;

    String readLine() {
        String rtn = pushedBackLine
        if (pushedBackLine == null){
            rtn = reader.readLine();
        }
        return rtn;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜