我通过eclipse将文本文件导入到我的java项目文件夹中。我正在尝试加载包含随机单词字典的文本,浏览它们并创建一个hashmap,其中单词的第一个字母是键,单词作为整体是值。
我在WordStore类中有一个方法:
public WordStore(String k) throws IOException {
map = new HashMap<String, List<String>>();
BufferedReader buffread = null;
File filename = null;
FileReader fread = null;
try{
filename = new File(k);
fread = new FileReader(filename);
buffread = new BufferedReader(fread);
String word ="";
while((word = buffread.readLine()) != null) {
if(word.length()<3) {
//don't add word less than 3 characters long
}
else {
String key = ""+(word.charAt(0));
put(key, word);
}
}
}
catch(IOException e) {
System.out.println("File not found exception caught!");
}
finally {
if(buffread != null) {
try {
buffread.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
}
我在WordStoreTest类中使用它:
import java.io.IOException;
public class WordStoreTest {
public static void main(String[] args) throws IOException {
WordStore store = new WordStore("nouns.txt");
System.out.println(store.getRandomWord("b"));
}
}
例外:
File not found exception caught! java.io.FileNotFoundException: nouns.txt (No such file or directory
at java.io.FileInputStream.open0(Native Method
at java.io.FileInputStream.open(FileInputStream.java:195
at java.io.FileInputStream.(FileInputStream.java:138
at java.io.FileReader.(FileReader.java:72
at WordStore.(WordStore.java:34
at WordStoreTest.main(WordStoreTest.java:14) null
答案 0 :(得分:0)
要访问项目结构中的文件,您需要重新创建从项目根目录到文件本身的路径。
假设文件位于src
文件夹中,例如
PROJECT
|
src
|
nouns.txt
aPackage
|
Main.java
以下代码成功:
public class Main {
public static void main(String[] args) {
System.out.println(Files.exists(Paths.get("src", "nouns.txt")));
}
}
答案 1 :(得分:0)
我总是使用BufferedReader
而不是从File
获取InputStream
。例如,您可以这样做:
String path = "/nouns.txt";
try {
InputStream is = this.getClass().getResourceAsStream("/misc/sample.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = bufferedReader.readLine();
for(; line!=null; line=bufferedReader.readLine()) {
System.out.println(line);
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
当然,此处的路径假定您的txt
文件位于src
下,而不是包,但您可以随时更改。您甚至可以创建第二个源文件夹并将其放在那里。