我试图使用类String的split方法将"loremIpsum.txt"
文件扫描到String,以将每个单词存储在数组的不同位置,最后使用HashSet查找文本中是否有任何单词重复。
但Eclipse无法识别该文件,即使它位于同一个包中。我想知道我的代码是否有问题?
package Lab5;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
public class Lorem {
public static void main(String[] args) {
String[] loremIpsum = null;
try {
loremIpsum = new Scanner(new File("loremIpsum.txt")).next().split(" ");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(loremIpsum.length);
HashSet h = new HashSet();
for(int i=0;i<loremIpsum.length;i++) {
String word=loremIpsum[i];
System.out.println(word);
if(h.contains(word)) {
System.out.println("we found a duplicate");
} else {
h.add(word);
}
}
}
}
该文件将在项目目录中查找(bin
和src
文件夹所在的位置)。将文件移到那里。
您需要将参数作为路径传递。
试试这个
String path = new File("").getAbsolutePath();
path.concat("/loremIpsum.txt");
loremIpsum = new Scanner(new File(path)).next().split(" ");
基本上你只是找到当前路径并附加你想要读取的文件名。就像其他人说的那样,你也可以将它移到工作目录中。
干杯!
当您使用相对路径调用File构造函数时,它相对于工作目录。
这通常与调用构造函数的代码不同。但这没关系,因为如果在运行应用程序时可以指定文件,那么无论如何都不想假设。
您可以在Arguments选项卡上的Eclipse运行配置中指定工作目录。
您可以使用File方法getAbsolutePath()查看如何解析相对路径。
try {
File myFile = new File("loremIpsum.txt");
System.out.println("Absolute path = " + myFile.getAbsolutePath() );
loremIpsum = new Scanner(myFile).next().split(" ");
...