I can't find the functionality to write the following code in Java (or Groovy)
reader.mark();   //(1)
reader.read();   //reads 'a'
reader.mark();   //(2)
reader.read();   //reads 'b'
reader.reset();  //back to (2)
reader.read();   //reads 'b'
reader.reset();  //back to (1)
reader.read();   //reads 'a'
reader.read();   //reads 'b'
Reader.mark(int) is a nice method but it doen't stack the marks, it only holds the most recent one..
Any support from Java library or am I on my own?
So I wrote it myself -.-
class CharReader {
    private Stack marks;
    private RandomAccessFile reader;
    CharReader(File file) {
        this.marks = new Stack();
        this.reader = new RandomAccessFile(file, 'r');
    }
    void mark() {
        long mark = reader.getFilePointer();
        marks.push(mark);
    }
    void reset() {
        if (marks.size() <= 0)
            return
        long mark = marks.pop();
        reader.seek(mark);
    }
    char peek() {
        mark();
        char nextChar = next();
        reset();
        return nextChar;
    }
    char next() {
        int nextChar;
        if ((nextChar = nextInt()) >= 0) {
            return (char) nextChar;
        }
        throw new IllegalStateException("Reader empty");
    }
    private int nextInt() {
        return reader.read();
    }
}
It's enough for my needs. Supports only single-byte chars ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With