我知道这个主题以前可能已经讨论过了,但我找不到我的问题的答案。
我有一个文件,其中包含一些我需要阅读的单词。
它在我的桌面版本上正常运行,但当我尝试在模拟器上运行时,我得到了 java.io.FileNotFoundException - no file found
。
我知道我必须以不同于桌面的方式加载文件。
如有任何帮助,我们将不胜感激。
这是读取文件的代码。
String line;
try {
BufferedReader br = new BufferedReader(new FileReader("words.txt"));
if (!br.ready()) {
throw new IOException();
}
while ((line = br.readLine()) != null) {
words.add(line);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
但这在 Android 上不起作用!!
仍然没有解决方案!!
最佳答案
您可以从 android 中的上下文访问文件。
Context Context;
AssetManager mngr = context.getAssets();
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(mngr.open("words.txt")));
if (!br.ready()) {
throw new IOException();
}
while ((line = br.readLine()) != null) {
words.add(line);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
或者试试这个:
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(getApplicationContext().getAssets().open("words.txt")));
if (!br.ready()) {
throw new IOException();
}
while ((line = br.readLine()) != null) {
words.add(line);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
关于java - 读取纯文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37228980/