简体   繁体   English

找不到Java .txt文件

[英]Java .txt file not found

For an assignment I need to call a method from another class SentenceChecker which uses a .txt file web2.txt. 对于分配,我需要从另一个使用.txt文件web2.txt的SentenceChecker类中调用一个方法。 I have placed Cryptography.java (in which I'm calling the method), Cryptography.class, SentenceChecker.java, SentenceChecker.class and the web2.txt files all in the same folder, and changed permissions for read and write for everyone but file still cannot be found. 我已经将Cryptography.java(我在其中调用该方法),Cryptography.class,SentenceChecker.java,SentenceChecker.class和web2.txt文件放置在同一文件夹中,并更改了除其他人以外的所有人的读写权限仍然找不到文件。 Please advise me on what to do? 请告诉我该怎么办? This is the code: 这是代码:

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;
 }
    }
}

The line new File("web2.txt") is a path which is relative to your current working directory , which is not necessarily where your files are. new File("web2.txt")new File("web2.txt")是相对于当前工作目录的路径,该目录不一定是文件所在的位置。

Assuming web2.txt is in your classpath, you should try something like this: 假设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”访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM