2015-10-31 88 views
1

對於任務,我需要從另一個類使用.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; 
} 
    } 
} 
+2

什麼是你的目錄結構? – shafeen

+0

如果您使用Eclipse,請使用Ctrl + Shift + f。幫助很多。 – Yoda

+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 
} 
+0

試過這個,但返回的錯誤是找不到符號:class URL。 – user5511249

+0

所以我需要弄清楚它是否在類路徑中? – user5511249

+0

是的,另一種可能需要考慮的方法是爲項目使用maven目錄結構,並將文件放在'resources /'目錄中,然後執行如下操作:'new File(SentenceChecker.class.getResource(「web2.txt 「).toURI());'但這需要你花一點時間熟悉maven文件結構。 – shafeen

0

另一種方案是把它放在一個位置(如桌面爲例),並使用路徑爲「C:\用戶\ Name \ Desktop \ web2.txt「來訪問它。