读取纯文本文件 [英] Reading a plain text file
本文介绍了读取纯文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道以前可能已经讨论过这个主题,但是我找不到我的问题的答案。
我有一个包含一些我需要阅读的单词的文件。
它可以在我的桌面版本上正常工作,但是如果我尝试在模拟器上运行,则会得到 java.io.FileNotFoundException-找不到文件
。
我知道我必须以不同于桌面的方式加载文件。
I know this topic probably has been covered before but I cant find an answer to the my problem.
I have a file that contains some words I need to read.
It works normally on my desktop version, but wen I try to run on an emulator, I get java.io.FileNotFoundException - no file found
.
I understand I have to load the file in a different way than the desktop.
任何帮助将不胜感激。
这是读取文件的代码。
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上不起作用!
but that doesn't work on Android!!
仍然没有解决方案!
推荐答案
您可以访问文件从Android中的上下文。
You can reach a file from context in 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);
}
这篇关于读取纯文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文