mark() method of StringReader

259 views Asked by At

My question pertains to the mark() method of Java's StringReader. Here is my scenario:

StringReader reader = new StringReader("Test123");

reader.mark(0);
boolean bool = doSomething(reader)//reads from reader with calls to mark() inside
if (bool == false) {
    reader.reset();
}

doSomethingElse(reader);

I want to recover my reader back to its original state if doSomething() returns false. Because reset() will only reset the reader back to the previously-called mark, and there are marks called from within the doSomething() method, it doesn't refer to the mark called one line before entering the doSomething() method. Is there a possible workaround to this? I appreciate the help!

2

There are 2 answers

2
Mike Baranczak On
  1. Since you know that doSomething() calls mark(), there's no point in calling mark() before that.

  2. Instead of resetting the StringReader, you can just create a new StringReader from the same string.

3
Timothy Wright On

The simple solution is to mark it before you reset:

StringReader reader = new StringReader("Test123");

boolean bool = doSomething(reader)//reads from reader with calls to mark() inside
if (bool == false) {
    reader.mark(0);
    reader.reset();
}

doSomethingElse(reader);

If you can't do that, you can wrap the initial mark position and reader in a custom object:

class MyReader {
   private int mark = 0;
   private StringReader reader;

   MyReader( StringReader reader, int mark ) {
      this.reader = reader;
      this.mark = mark;
   }

   public StringReader getReader() { return reader; }

   public void hardReset() {
      reader.mark(mark);
      reader.reset();
   }
}

You would use it like this:

StringReader reader = new StringReader("Test123");
MyReader mr = new MyReader( reader, 0 );
boolean bool = doSomething(mr); // mr.getReader().mark(i); 
if (bool == false) {
     mr.hardReset();
}

doSomethingElse(mr);