读取纯文本文件
Reading a plain text file
我知道这个话题以前可能已经讨论过了,但我找不到我的问题的答案。
我有一个文件,其中包含一些我需要阅读的单词。
它在我的桌面版本上正常工作,但当我尝试在模拟器上 运行 时,我得到 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 不起作用!!
仍然没有解决方案!!
资产是您开发机器上的文件。它们不是设备上的文件。
要获得资产 InputStream
,use open()
on an AssetManager
。您可以通过在 Activity
、Service
或其他 Context
上调用 getAssets()
来获得 AssetManager
。
您可以从 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.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 不起作用!!
仍然没有解决方案!!
资产是您开发机器上的文件。它们不是设备上的文件。
要获得资产 InputStream
,use open()
on an AssetManager
。您可以通过在 Activity
、Service
或其他 Context
上调用 getAssets()
来获得 AssetManager
。
您可以从 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);
}