【问题标题】:How should I read a text file without getting FileNotFoundException?我应该如何阅读文本文件而不得到 FileNotFoundException?
【发布时间】:2019-01-02 01:52:36
【问题描述】:

我正在为我的计算机科学课的期末作业编写一个单词搜索生成器程序。

我创建了一个名为“Words”的文本文件,其中包含字母表中 26 个字母中的每个字母的 10 个单词。我通过阅读此文本文件并将其存储在数组列表中来引用此文本文件。

我使用了我在此处获得的反馈并进行了一些更改。我已经定义了fileName 是什么,并且我已经插入了我的文本文件的确切位置。

这是我更新的代码:

public static List<String> readWords () throws IOException {

        String fileName = ("C:\\Users\\Dell\\workspace\\Final Summative\\src\\Words.txt");

        int maxLength = Math.max(rows, cols);

        List<String> words = new ArrayList<>(); // The words from the Words text file will be stored in this array list

        try (Scanner sc = new Scanner(new FileReader(fileName))) {      

            while (sc.hasNextLine()) {

                String s = sc.next().trim().toLowerCase();

                if (s.matches("^[a-z]{3," + maxLength + "}$")) { // We will pick only words with length = 3 and max. length, and [a-z] inside

                    words.add(s.toUpperCase());

                }//end of if

            }//end of while loop

        } catch (IOException e) {

            // Manage the error!

            e.printStackTrace();

        }//end of catch

        return words;

    }//end of readWords(fileName)

我现在运行代码时收到FileNotFoundException。我仔细检查了我的文本文件是否在正确的文件夹中,但我仍然遇到此错误。它是这样说的:

java.io.FileNotFoundException: C:\Users\Dell\workspace\Final Summative\src\Words.txt (The system cannot find the file specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileReader.<init>(Unknown Source)
    at WordSearch.readWords(WordSearch.java:76)

【问题讨论】:

  • 在发布之前进行一些调试工作,并准确指出代码中可能存在问题的位置确实是您的责任。
  • fileName 指向的位置不正确。你只需要解决这个问题。
  • 提示:您需要将文件放在程序“可访问的地方”——最简单的方法:在 Java CLASSPATH 的某个地方。这就是FileNotFoundException 告诉你的。您的“项目”的文件夹结构是什么? Words 文件在哪里?
  • @YashviShah 我不知道,因为我不知道您要读取的文件的实际路径。您只需要验证它们是否匹配。
  • // Manage the error! 不要只评论,改成e.printStackTrace();

标签: java file-io computer-science filenotfoundexception file-read


【解决方案1】:

首先,s.matches("^[a-z]{3," + maxLength + "]$" 中的括号 { } 没有正确闭合。
而且很可能没有正确给出文件名。
检查它是否类似于:readWords("C:/Users/Username/Desktop/words.txt"),以防您的文本文件在桌面上。

【讨论】:

    【解决方案2】:

    如果您真正需要做的只是读取文件中的所有行,那么在更现代的 Java 版本中会有一个快捷方式:Files.lines。

    事实上,如果您有一个匹配单词的模式,那么您可以使用Matcher.results 和MatchResult.group 一次性完成所有操作:

    Files.lines(path)
        .map(pattern::matcher)
        .flatMap(Matcher::results)
        .map(MatchResult::group)
        .collect(Collector.toList());
    

    但是我不确定你是否研究过流或允许使用哪些库。

    请注意,我在这里收集到了一个列表,尽管收集到一个集合(假设您不需要了解重复项)或一个地图(如果这对第一个字母很重要,则以第一个字母作为键)可能更有意义词的使用)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      相关资源
      最近更新 更多