java - 文件读取器库输出 null

标签 java io bufferedreader

因为懒得每次做项目都重写文件管理器,所以就做一个文件IO库。当我运行它时,我得到:

null
null
null

它查找文件中有多少行,但将它们全部设置为空。我该如何解决这个问题?

文件管理器:

package textfiles;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;

public class KezelFile {

    private String path;
    BufferedReader buff;

    public KezelFile(String filePath) throws IOException {
        path = filePath;
        openFile();
    }

    public void openFile() throws IOException {
        FileReader read = new FileReader(path);
        buff = new BufferedReader(read);
    }

    public String[] toStringArray() throws IOException {

        int numberOfLines = readLines();
        String[] textData = new String[numberOfLines];

        int i;

        for (i=0; i < numberOfLines; i++) {
        textData[i] = buff.readLine();

        }
        return textData;
    }

    int readLines() throws IOException {

        String lines;
        int noLines = 0;

        while ((lines = buff.readLine()) != null) {
            noLines++;
        }

        return noLines;
    }

    public void closeFile() throws IOException {
        buff.close();
    }

}

主类:

package textfiles;
import java.io.IOException;

public class FileData {

    public static void main(String[] args) throws IOException {

        String filePath = "C:/test.txt";

        try {
            KezelFile file = new KezelFile(filePath);
            String[] aryLines = file.toStringArray();

            int i;
            for (i=0; i < aryLines.length; i++) {
            System.out.println(aryLines[i]);
            }
            file.closeFile();
        }

        catch (IOException error){
            System.out.println(error.getMessage());
        }

    }

}

最佳答案

读取完所有行后,您将无法再次读取这些行,直到再次打开文件。只是因为 readLine() 是从不同的方法调用的,所以它不会“重置”阅读器。

更好的解决方案是只读取文件一次。我建议您将这些行读入 List<String>或者甚至在您阅读文件时更好地处理该文件,并且您也不需要该集合。

顺便说一句,在 Java 8 中你可以这样写

Files.lines(filename).forEach(System.out::println);

也许是时候尝试 Java8 了;)

关于java - 文件读取器库输出 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27462870/

相关文章:

Java gui,尝试转换为 gui 时的客户端问题

java - Java 中 BufferedReader 偶尔出现错误

java - 如何在运行时修改 Jar 文件内的文本文件?

python - 围绕文件对象堆叠过滤器

java - 每个按钮单击以更改 TextView

Java - 使用格式化程序标志从左侧截断字符串

java - JTable 更改后 JScrollBar 不会更新其最大值

java - 文件 deleteOnExit() 函数即使在文件被删除后仍保持引用指针打开

java - 如何克隆或复制 BufferedReader?

java - 如何将自定义 validator 与 dropwizard 一起使用?