我的目标是最终制作一个拼写检查器,但我需要一个单词词典来做到这一点。阅读txt文件和编写词典
这里我试图让用户输入任意数量的文本文件,只要文件名之间有一个空格(“novel1.txt novel2.txt novel3.txt”)。
我将使用这些小说中的每个单词写入单个单词(即单词词典)中单个单词的.dat文件。但是,即使我知道我有该文件,但我仍在Scanner read = new Scanner(new File(filenames[i]));
处发现文件未找到错误。
我甚至试图把它放在源码包中,以确保它可以被发现。
在我的代码最底层是一个我跑过的小测试(首先注释掉其他代码),它确实打印出“war.txt不是文件”,尽管我可以清楚地看到我有txt文件并输入正确。
有人可以告诉我为什么java没有看到我的txt文件或者可能不认为这是一个正常的文件?
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the file names exactly.");
String userInput = in.nextLine();
String[] filenames = userInput.split(" "); // turning user input string into a string array so I can look at each string individually
// takes each individual string from filenames and turns each one into the file
// that the string should represent then adds the file's contents to my dictionary
for(int i = 0; i < filenames.length; i++){
Scanner read = new Scanner(new File(filenames[i]));
String word = null;
while(read.hasNext()){
if(read.next().length() >= 2){
word = read.next();
// write word into myDict.dat
}
System.out.println(word);
}
}
File war = new File("war.txt");
if(!war.isFile()){
System.out.println(war + " isn't a file.");
}
}
你如何运行你的代码?你的'class'和你的'txt'文件在哪个目录中?有没有一样的? – SubOptimal
只是一个输入建议:尝试读取行,直到终端行,例如''结束'',它会使文件更容易输入空格等等(你可以疯狂地做些事情,比如子串和引用/解析等等,但这会更简单) – Rogue
@SubOptimal我已经把txt文件与我的程序在同一个目录中。 –