繁体   English   中英

如何在不彻底更改程序的情况下用Java重置FileReader?

[英]How to reset FileReader in java without having to change my program drastically?

我发现FileReader only扫描一次文件。 之后,您必须关闭它并重新初始化它才能重新扫描文件(如果要在程序中进行)。 我已经在其他博客和stackoverflow问题中阅读了有关此内容的信息,但其中大多数提到了BufferedReader或其他类型的阅读器。 问题是我已经使用FileReader完成了程序,并且不想将所有内容都更改为BufferedReader ,那么是否仍然可以在不引入任何其他类或方法的情况下重置文件指针? 还是反正只是将BufferedReader包装在我已经存在的FileReader周围? 这是我专门为这个问题编写的一小段代码,如果我可以将BufferedReader包裹在FileReader周围,​​我希望您使用此代码段来实现。

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()时,您应该变得轻松自在:
BufferedReadermark方法: public void mark(int readAheadLimit) throws IOException 这是从javadoc复制的用法:

限制在仍保留标记的情况下可以读取的字符数。 读取达到或超过此限制的字符后,尝试重置流可能会失败。 大于输入缓冲区大小的限制值将导致分配新缓冲区,其大小不小于限制。 因此,应谨慎使用较大的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM