java - 如何在 java 中重置 FileReader 而无需大幅更改我的程序?

标签 java file-io bufferedreader reset filereader

我发现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/

相关文章:

java - 无法在 AWS 中使用 JDBC 访问 RDS

java - 如何使用FileWriter将内容写入文件中的特定位置?

java - 如何解决 Future<CAP#1> 无法转换为 Future<Void> 的问题?

java - 泽西 Json 和 Pojo

java - OriginalDestination 可以用作死信队列使用者的选择器吗?

Java - 读取文件夹中的所有 .txt 文件

Java字符串程序

c - C 中的文件处理和图形 ADT

java - 如何在 java 中将 mp4 转换为 mp3

java - 如何根据这段代码中的某些条件来显示图像和不同的变量?