未找到Java .txt文件
对于任务,我需要从另一个类使用.txt文件web2.txt的类SentenceChecker调用方法。我已经将Cryptography.java(在其中调用方法),Cryptography.class,SentenceChecker.java,SentenceChecker.class和web2.txt文件放在同一个文件夹中,并且更改了每个人的读写权限,但是文件仍然无法找到。请告诉我该怎么做?这是代码:未找到Java .txt文件
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class SentenceChecker {
final static int NUMBER_WORDS = 234936;
public static String[] wordList = initializeList();
public static int countEnglishWords(String input) {
String[] allWords = input.split(" ");
int totalWords = 0;
for (int i=0; i < allWords.length; i++) {
String transformed = allWords[i].toLowerCase();
transformed = transformed.replaceAll("[^A-Za-z]", "");
if (findWord(transformed)) {
totalWords++;
}
}
return totalWords;
}
private static boolean findWord(String input) {
int left = 0;
int right = wordList.length - 1;
while (left <= right) {
int center = (left + right)/2;
if (wordList[center].equals(input)) {
return true;
}
if (wordList[center].compareTo(input) < 0) {
left = center + 1;
}
else {
right = center - 1;
}
}
return false;
}
private static String[] initializeList() {
try {
Scanner scanner = new Scanner(new File("web2.txt"));
String[] words = new String[NUMBER_WORDS];
int i=0;
while (scanner.hasNextLine()) {
words[i] = scanner.nextLine().toLowerCase();
i++;
}
return words;
}
catch (FileNotFoundException e) {
System.out.println("WARNING: The file web2.txt was not found. Is it in the same directory as your other java files?");
return null;
}
}
}
线new File("web2.txt")
是相对于你的当前工作目录,这不一定是在您的文件的路径。
假设web2.txt
是在类路径中,你应该尝试这样的事:
URL path = ClassLoader.getSystemResource("web2.txt");
File f = null;
if(path != null) { // file exists
f = new File(path.toURI());
} else {
//The file was not found, insert error handling here
}
试过这个,但返回的错误是找不到符号:class URL。 – user5511249
所以我需要弄清楚它是否在类路径中? – user5511249
是的,另一种可能需要考虑的方法是为项目使用maven目录结构,并将文件放在'resources /'目录中,然后执行如下操作:'new File(SentenceChecker.class.getResource(“web2.txt “).toURI());'但这需要你花一点时间熟悉maven文件结构。 – shafeen
另一种方案是把它放在一个位置(如桌面为例),并使用路径为“C:\用户\ Name \ Desktop \ web2.txt“来访问它。
什么是你的目录结构? – shafeen
如果您使用Eclipse,请使用Ctrl + Shift + f。帮助很多。 – Yoda
尝试包括文件路径,而不仅仅是文件名。 –