【发布时间】: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