java - 在 Android SDK 中导入文本文件

标签 java android import sdk text-files

过去几天我一直在尝试读取文件,并尝试按照其他答案进行操作,但没有成功。这是我目前必须导入文本文件的代码:

    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/

相关文章:

android - 即使使用 commit(),SharedPreference 值也会在每次登录时变回

Android build.gradle - 库冲突

python - 为什么在使用 execfile() 运行的 python 脚本中 import 不能防止 NameError?

python - 适用于虚线模块的 `imp.find_module` 版本

Python模块之间的依赖关系

java - 成功后,步骤无法在 travis-ci 构建中的项目根目录下找到文件

java - 将 EntityGraph 与 Hibernate 搜索 ORM 结合使用

android - 解析和 Twilio

java - 通过PreparedStatement更改受更新影响的列

java - 简单的portlet jsp页面流问题