找不到Java.txt文件
对于赋值,我需要从另一个使用.txt文件web2.txt的类SentenceChecker调用一个方法。我已将Cryptography.java(我在其中调用该方法)、Cryptography.class、SentenceChecker.java、SentenceChecker.class和web2.txt文件都放在同一个文件夹中,并更改了每个人的读写权限,但仍然找不到该文件。请告诉我该怎么办?代码如下:找不到Java.txt文件,java,Java,对于赋值,我需要从另一个使用.txt文件web2.txt的类SentenceChecker调用一个方法。我已将Cryptography.java(我在其中调用该方法)、Cryptography.class、SentenceChecker.java、SentenceChecker.class和web2.txt文件都放在同一个文件夹中,并更改了每个人的读写权限,但仍然找不到该文件。请告诉我该怎么办?代码如下: import java.util.Scanner; import java.io.File
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;
}
}
}
import java.util.Scanner;
导入java.io.File;
导入java.io.FileNotFoundException;
公共类句子检查器{
最终静态整数_字=234936;
公共静态字符串[]wordList=initializeList();
公共静态int countEnglishWords(字符串输入){
String[]allWords=input.split(“”);
整数totalWords=0;
for(int i=0;i新文件(“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
}
另一种解决方案是将其放置在一个位置(例如桌面),并使用路径“C:\Users\Name\desktop\web2.txt”要访问它。您的目录结构是什么?如果您使用Eclipse,请使用ctrl+shift+f。帮助很大。尝试包括文件路径,而不仅仅是文件名。目录结构是/Users/name/Downloads/folder1/web2.txt尝试了这一点,但返回的错误是找不到符号:类URL。因此我需要确定它是否在类路径中?是的,另一种方法是使用项目的Maven目录结构,将文件放在<代码>资源/< /代码>目录中,然后执行这样的代码<代码>新文件(SturnChigk.Cype .GETRealver(“Web2..txt”).TURIL());但这需要您花一点时间熟悉maven文件结构。