gpt4 book ai didi

找不到 Java .txt 文件

转载 作者:太空宇宙 更新时间:2023-11-04 13:17:04 25 4
gpt4 key购买 nike

对于一项作业,我需要调用另一个类 SentenceChecker 中的方法,该类使用 .txt 文件 web2.txt。我已将 Cryptography.java (在其中调用该方法)、Cryptography.class、SentenceChecker.java、SentenceChecker.class 和 web2.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
}

关于找不到 Java .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33457010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com