Tuesday, May 28, 2013

FileReader - How Can I Reset The File Pointer to the Beginning of the File in Java?

FileReader - How Can I Reset The File Pointer to the Beginning of the File in Java? 
(or)
Mark() and reset() not supported error for FileReader Class ?!?

The answer is just one line : You cannot work with mark() and reset() methods with FileReader. DON'T WORRY. You
have a one line solution to make it worked out.

Suppose your code is similar to the one shown below and you are trying with mark() and reset() as shown here:

FileReader file=new FileReader("apple.txt");
file.mark(25);
while((ch=file.read())!=-1)
Sytem.out.print((char) ch);
file.reset();

And you will get error like: "mark() not supported

So, the solution is using BufferedReader which supports both mark() and reset(). See the following code
 snippet on how to do modifications in your code.

FileReader file=new FileReader("apple.txt");
BufferedReader b=new BufferedReader(file);
b.mark(25);
while((ch=b.read())!=-1)
Sytem.out.print((char) ch);
b.reset();

5 comments:

  1. hffgh kacke brrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr!!!

    ReplyDelete
    Replies
    1. What's this ?
      Give meaningful comments; my blog is not a garbage to collect your beautiful phrases

      Delete
  2. so, ! mark() and reset() are methods of class BufferedReader ?
    and i have another doubt !
    how to insert words/character inbetween characters! in java!
    i'm new to java! i work on php,Node.js!

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. any alternatives for mark() and reset() if we are using file reader?

    ReplyDelete