Reputation: 2029
I have found out that FileReader
scans the file only
once. After that you have to close it and re-initialize it to re-scan the file if you want in a program. I have read about this in other blogs and stackoverflow questions, but most of them mentioned BufferedReader
or some other type of readers. The problem is that I have already finished my program using FileReader
and I don't want to change everything to BufferedReader
, so is there anyway to reset the file pointer without bringing in any other classes or methods? or is there anyway to just wrap a BufferedReader
around my already existing FileReader
? Here is a small code that I wrote specifically for this question and if I can wrap a BufferedReader
around my FileReader
, I want you to do it with this code snippet.
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class Files {
public static void main(String args[]) throws IOException{
File f = new File("input.txt");
FileReader fr = new FileReader(f);
int ch;
while((ch = fr.read()) != -1){
// I am just exhausting the file pointer to go to EOF
}
while((ch = fr.read()) != -1){
/*Since fr has been exhausted, it's unable to re-read the file now and hence
my output is empty*/
System.out.print((char) ch);
}
}
}
Thanks.
Upvotes: 1
Views: 7280
Reputation: 134
Use java.io.RandomAccessFile
like this:
RandomAccessFile f = new RandomAccessFile("input.txt","r"); // r=read-only
int ch;
while ((ch = f.read()) != -1) {
// read once
}
f.seek(0); // seek to beginning
while ((ch = f.read()) != -1) {
// read again
}
EIDT ------------
BufferedReader
also works:
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
br.mark(1000); // mark a position
int ch;
if ((ch = br.read()) != -1) {
// read once
}
br.reset(); // reset to the last mark
if ((ch = br.read()) != -1) {
// read again
}
But you should be cafeful when using mark()
:
The mark
method in BufferedReader
: public void mark(int readAheadLimit) throws IOException
. Here is it's usage copied from javadoc :
Limit on the number of characters that may be read while still preserving the mark. An attempt to reset the stream after reading characters up to this limit or beyond may fail. A limit value larger than the size of the input buffer will cause a new buffer to be allocated whose size is no smaller than limit. Therefore large values should be used with care.
Upvotes: 2