1

File objects in python have a method called seek that allows you to place the file bookmark anywhere in the file. In particular seek(0) puts the file bookmark back at the beginning of a file.

Can a similar thing be done to a BufferedReader in Java, or do you just have to make a new one?

ncmathsadist
  • 4,684
  • 3
  • 29
  • 45

2 Answers2

2

You cannot do that on a BufferedReader because he can only return a specified amount of bytes (in fact his buffer size).
What you can do:

FileInputStream fileinputStream = ...;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileinputStream));


// reset to the beginning of file and overwrite old buffered reader
fileinputStream.getChannel().position(0);
bufferedReader = new BufferedReader(new InputStreamReader(fileinputStream));

Here is some doc about the FileChannel I used with fileinputStream.getChannel():

https://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html

So to your question: Yes, you need to create a new one

ItFreak
  • 2,299
  • 5
  • 21
  • 45
  • In Java you can also `seek` on a `RandomAccessFile` object. https://docs.oracle.com/javase/10/docs/api/java/io/RandomAccessFile.html – markspace Apr 17 '19 at 13:15
2

In a word, no. All you can do is to make a new one. Mark/reset only works if the file is smaller than the buffer size. This is, of course, unacceptable.

ncmathsadist
  • 4,684
  • 3
  • 29
  • 45