如何连续读取一个文件?

How to read a file continuously?

我想连续读取一个文件,我的意思是如果我找到一个文件的结尾,我想从头开始再读一遍。所以我正在重置流,但它不起作用。这是我的代码。

 br = new BufferedReader(new FileReader("E:\Abc.txt"));
        while(true)
        {

            sCurrentLine = br.readLine();
            if(sCurrentLine!=null)
                System.out.println(sCurrentLine);
            else
                br.reset();

        } 

谁能帮我解决这个问题。

初始化后添加br.mark(100);br

Marks the present position in the stream. Subsequent calls to reset()
will attempt to reposition the stream to this point.

关于参数 readAheadLimit:

readAheadLimit 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.

下面的代码会不断打印文件的内容/home/user/temp/reader.test

    BufferedReader br = new BufferedReader(new FileReader("/home/user/temp/reader.test"));
    String sCurrentLine;

    br.mark(100);
    while(true)
    {
        sCurrentLine = br.readLine();
        if(sCurrentLine!=null)
            System.out.println(sCurrentLine);
        else
            br.reset();
    } 

您最好的选择可能是重新创建 BufferedReader 一次 readLine() returns null.

例如:

String filename = "[filename]";
BufferedReader reader = new BufferedReader(new FileReader(filename));

while (true) {
    String line = reader.readLine();
    if (line != null)
        // Use line
    else {
        reader.close();
        reader = new BufferedReader(new FileReader(filename));
    }
}

这样做的好处是总是直接从文件中读取而不会一次在内存中存储太多内容,如果像您所说的那样包含五千行,这可能是一个问题。

br = new BufferedReader(new FileReader("E:\Abc.txt"));
while(true) {
     sCurrentLine = br.readLine();
     if(sCurrentLine!=null) {
          System.out.println(sCurrentLine);
     } else {
          br.close();
          br = new BufferedReader(new FileReader("E:\Abc.txt"));
     }
}

所以它将用一个新的 BufferedReader 重新启动 :)