Multiple tags in Reader

I cannot find functionality for writing 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 good method, but it does not add tags, it contains only the last one.

Any support from the Java library or myself?

+6
source share
2 answers

So, I wrote this 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(); } } 

This is enough for my needs. Only supports one char byte; -)

+8
source

You can try to implement something around PushBackReader , which has an unread method that allows you to push unwanted characters into the pushback buffer.

 char a, b; // reader holds "ab" a = reader.read(); // reader holds "b" b = reader.read(); // reader holds "" reader.unread(b); // reader holds "b" b = reader.read(); // reader holds "" reader.unread(b); // reader holds "b" reader.unread(a); // reader holds "ab" a = reader.read(); // reader holds "b" b = reader.read(); // reader holds "" 

For parsing applications, this kind of tool is enough to do what you need.

Another option is for each nesting layer that needs to be labeled in order to build a new Reader on top of the one with which they were transferred, and mark this instead.

0
source

All Articles