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.
BufferedReaderwill not really solve the problem. You would have to make the buffer so big that the whole file is kept in memory. What's so bad about reopening the file?reset(). There is no hard guarantee however on cross-platform compatibility.