过去几天我一直在尝试读取文件,并尝试按照其他答案进行操作,但没有成功。这是我目前必须导入文本文件的代码:
public ArrayList<String> crteDict() {
try {
BufferedReader br = new BufferedReader
(new FileReader("/program/res/raw/levels.txt"));
String line;
while ((line = br.readLine()) != null) {
String[] linewrds = line.split(" ");
words.add(linewrds[0].toLowerCase());
// process the line.
}
br.close();
}
catch (FileNotFoundException fe){
fe.printStackTrace();
它的目的是读取文本文件并创建一长串单词。它一直以 FileNotFoundException 结束。 请让我知道任何答案。 谢谢!
最佳答案
如果你的文件存放在android工程的res/raw
文件夹下,你可以这样读取,这段代码必须在Activity
类中,如this.getResources()
引用Context.getResources()
:
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = this.getResources().openRawResource(R.raw.levels);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
// While the BufferedReader readLine is not null
while ((readLine = br.readLine()) != null) {
Log.d("TEXT", readLine);
}
// Close the InputStream and BufferedReader
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
关于java - 在 Android SDK 中导入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20753792/