我发现FileReader
只扫描文件一次
。之后,如果您想在程序中使用,您必须关闭它并重新初始化它以重新扫描文件。我在其他博客和 stackoverflow 问题中读到过相关内容,但大多数都提到了 BufferedReader 或其他类型的阅读器。问题是我已经使用 FileReader
完成了我的程序,并且我不想将所有内容更改为 BufferedReader
,那么有没有办法在不引入的情况下重置文件指针还有其他类或方法吗?或者是否可以将 BufferedReader 包裹在我已经存在的 FileReader 周围?这是我专门为这个问题编写的一个小代码,如果我可以在我的 FileReader
周围包装一个 BufferedReader
,我希望您使用此代码片段来完成它。
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);
}
}
}
谢谢。
最佳答案
像这样使用java.io.RandomAccessFile
:
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
也可以工作:
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
}
但是使用 mark()
时你应该保持自信:
BufferedReader
中的 mark
方法:public void mark(int readAheadLimit) 抛出 IOException
。这是从 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.
关于java - 如何在 java 中重置 FileReader 而无需大幅更改我的程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36787727/