java - 读取纯文本文件

标签 java android file load bufferedreader

我知道这个主题以前可能已经讨论过了,但我找不到我的问题的答案。
我有一个文件,其中包含一些我需要阅读的单词。
它在我的桌面版本上正常运行,但当我尝试在模拟器上运行时,我得到了 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/

相关文章:

android - AppCompat Material Style 部件色调错误

ruby 文件 IO : Can't open url as File object

java - 在 Java 中检查文件中的某个字符串

java - 在我的网页中取一个3rd party applet的 "screenshot"

java - 如何快速滚动卡片 View

android - 迁移到Gradle后,ActionBar为null

android - 仅在 Android 和 Blackberry 中使用 Facebook 身份验证?

java - 在 Java 中列出文件的最快方法

java - 硬编码字符串有效,输入字符串无效

java - 与 Java 程序一起使用的最佳数据库是什么?