對於任務,我需要從另一個類使用.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;
}
}
}
什麼是你的目錄結構? – shafeen
如果您使用Eclipse,請使用Ctrl + Shift + f。幫助很多。 – Yoda
嘗試包括文件路徑,而不僅僅是文件名。 –