Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple marks in Reader

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?

like image 687
emesx Avatar asked Dec 18 '12 20:12

emesx


1 Answers

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

like image 177
emesx Avatar answered Oct 06 '22 03:10

emesx