【问题标题】:Reading in text file in Java在Java中读取文本文件
【发布时间】:2011-12-31 13:20:20
【问题描述】:

我编写了一些代码来读取文本文件并返回一个数组,其中每一行都存储在一个元素中。我一生都无法弄清楚为什么这不起作用……有人可以快速浏览一下吗? System.out.println(line) 的输出;是空的,所以我猜在读取该行时有问题,但我不明白为什么。顺便说一句,我传递给它的文件肯定有东西!

public InOutSys(String filename) {
    try {
        file = new File(filename);
        br = new BufferedReader(new FileReader(file));
        bw = new BufferedWriter(new FileWriter(file));
    } catch (Exception e) {
        e.printStackTrace();
    }
}



public String[] readFile() { 

    ArrayList<String> dataList = new ArrayList<String>();   // use ArrayList because it can expand automatically
    try {
        String line;

        // Read in lines of the document until you read a null line
        do {
            line = br.readLine();
            System.out.println(line);
            dataList.add(line);
        } while (line != null && !line.isEmpty());
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    //  Convert the ArrayList into an Array
    String[] dataArr = new String[dataList.size()];
    dataArr = dataList.toArray(dataArr);

    // Test
    for (String s : dataArr)
        System.out.println(s);

    return dataArr; // Returns an array containing the separate lines of the
    // file
}

【问题讨论】:

  • 你确定你的文件没问题吗?您是否在正确的位置(相对于用户主管)寻找文件?
  • file/br/bw 在哪里声明? InOutSys 和 readFile 是公开的,但第二个关闭 br。如何避免在关闭的 br 上调用 readFile?

标签: java bufferedreader


【解决方案1】:

首先,在使用 new FileWriter(file) 打开 FileReader 后打开 FileWriter 一次,它以创建模式打开文件。所以在你运行你的程序后它将是一个空文件。

其次,你的文件中有空行吗?如果是这样,!line.isEmpty() 将终止你的 do-while-loop。

【讨论】:

    【解决方案2】:

    您正在对正在读取的文件使用 FileWriter,因此 FileWriter 会清除文件的内容。不要同时读写同一个文件。

    还有:

    • 不要假设文件包含一行。不应使用 do/while 循环,而应使用 while 循环;
    • 始终在 finally 块中关闭 Steam、读者和作者;
    • catch(Exception) 是一种不好的做法。只捕获你想要的异常,并且可以处理。否则,让他们上栈。

    【讨论】:

      【解决方案3】:

      我不确定您是在寻找改进您提供的代码的方法,还是只是在寻找标题所说的“在 Java 中读取文本文件”的解决方案,但如果您正在寻找解决方案,我'd 建议使用 apache commons io 为你做这件事。 FileUtils 中的 readLines 方法将完全按照您的要求进行。

      如果你想从一个好的例子中学习,FileUtils 是开源的,所以你可以通过looking at the source 来看看他们是如何选择实现它的。

      【讨论】:

        【解决方案4】:

        您的问题有几个可能的原因:

        • 文件路径不正确
        • 您不应该尝试同时读/写同一个文件
        • 在构造函数中初始化缓冲区并不是一个好主意,想想看 - 某些方法可能会关闭缓冲区,使其对于该方法或其他方法的后续调用无效
        • 循环条件不正确

        最好试试这种阅读方式:

        try {
            String line = null;
            BufferedReader br = new BufferedReader(new FileReader(file));
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                dataList.add(line);
            }
        } finally {
            if (br != null)
                br.close();
        }
        

        【讨论】:

          猜你喜欢
          • 2016-02-29
          • 1970-01-01
          • 1970-01-01
          • 2016-08-08
          • 1970-01-01
          • 1970-01-01
          • 2011-01-12
          • 1970-01-01
          相关资源
          最近更新 更多