找不到Java .txt文件

时间:2015-10-31 21:49:45

标签: 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.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;
 }
    }
}

2 个答案:

答案 0 :(得分:0)

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
}

答案 1 :(得分:0)

另一种解决方案是将其放在一个位置(例如桌面)并使用路径&#34; C:\ Users \ Name \ Desktop \ web2.txt&#34;访问它。