【问题标题】:File reader library outputting null文件阅读器库输出 null
【发布时间】:2014-12-13 19:40:55
【问题描述】:

因为我每次做项目都懒得重写文件管理器,所以我在做一个文件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());
        }

    }

}

【问题讨论】:

  • 请不要重新发明轮子——没有人需要方轮。尤其是没有一个缓慢穿刺的。只需使用 Files 实用程序类。

标签: java io bufferedreader


【解决方案1】:

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

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

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

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

也许是时候尝试 Java8 了;)

【讨论】:

  • 更好的解决方案是使用现有功能 - Files.readAllLinesFiles.lines...
  • @BoristheSpider 假设你有 Java 8,是的。如果你没有 Java 8,也许你应该;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-19
  • 1970-01-01
  • 2019-09-01
  • 2012-05-03
  • 1970-01-01
  • 2011-05-05
相关资源
最近更新 更多