[英]reading txt file and writing a dictionary
我的目标是最终制作一个拼写检查器,但我需要一个字典来做到这一点。
在这里,我试图允许用户输入任意数量的文本文件,只要文件名之间有空格(“ novel1.txt novel2.txt novel3.txt”)即可。
我将使用这些小说中的每个单词,将它们写在.dat文件中,这些文件在单独的行上(即单词词典)。 但是我在Scanner read = new Scanner(new File(filenames[i]));
发现文件未找到错误Scanner read = new Scanner(new File(filenames[i]));
即使我知道我有文件。
我什至尝试将其放在源代码包中以确保可以找到它。
在我的代码的最底部是我运行的一个小测试(首先注释掉其他代码),尽管我可以清楚地看到我有txt文件,但它确实显示“ war.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.");
}
}
我相信您以错误的方式做某事。 请尝试以下示例,并将其与您的实际文件位置进行比较。
演示程序
import java.io.*;
class Demo {
public static void main(String[] args) throws IOException {
File war = new File("war.txt");
if(!war.isFile()){
System.out.println(war + " isn't a file.");
} else {
System.out.println(war + " is a file.");
}
}
}
编译并运行它
javac Demo.java
java Demo
产量
war.txt isn't a file.
现在在同一目录中创建war.txt
echo "foobar" > war.txt
再次运行代码
java Demo
产量
war.txt is a file.
对于FileNotFoundException
,如果仅插入文件名,请确保文件位于类路径中(例如,如果使用eclipse,则将文件放在项目的根文件夹中)。
对于war.txt
问题,您应该这样做:
File war = new File("war.txt");
if (!war.exists()) {
war.createNewFile();
}
if(!war.isFile()){
System.out.println(war + " isn't a file.");
}
这是因为当您执行File war = new File("war.txt");
您没有创建文件,必须使用war.createNewFile();
显式创建它war.createNewFile();
。
最后,在这里注意:
if(read.next().length() >= 2){
word = read.next();
// write word into myDict.dat
}
System.out.println(word);
您执行两次read.next()
而第二次不执行read.hasNext()
。 您应该这样写:
while(read.hasNext()){
String next = read.next();
if(next.length() >= 2){
word = next;
// write word into myDict.dat
}
System.out.println(word);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.