java - 为什么在 java 中使用 FileReader 时找不到我的文件

标签 java android file android-studio filereader

我正在尝试查找我在 android studio 中保存的文件。我已经尝试了一切:放置完整目录,将文件放入该目录中的新文件夹中,使用 file.getAbsolutePath() ,在之前声明文件或将文件直接放入阅读器(BufferedReader r = new BufferedReader(new FileReader("history.txt")); 这是代码:

        File file = new File("Extra Files/history.txt");
        BufferedReader r = new BufferedReader(new FileReader(file.getAbsolutePath()));
        String scores = r.readLine();
        r.close();

无论我尝试什么,它似乎都不起作用任何其他想法,你不能在 android studio 中使用这样的文本文件吗???

    public void write_score(int ns) throws IOException {
        File file = new File(context.getFilesDir(), "history.txt");
        BufferedWriter w = new BufferedWriter(new FileWriter(file));
        w.append(String.valueOf(ns)).append(",");
        w.close();
    }

最佳答案

如果您只需要从文件中读取,您可以将其放入 asset 或 res/raw 文件夹中,并使用 context.getAssets().open("filename") or context.getResources().openRawResource(R.raw.resourceName) 从中读取。获取输入流,然后使用 BufferedReader(new InputStreamReader(fileStream))以获得读者。如果没有,this post ,应该有答案让您从不同的文件夹中读取。

如果您想写入它,一种方法是使用 app-specific internal files可以通过

访问
File file = new File(context.getFilesDir(), filename);

但您首先需要使用file.createNewFile()创建history.txt文件并用您想要的任何内容填充它,因为当您第一次尝试访问它时它还不存在。之后应该就好了。我希望这会有所帮助。

编辑:

这是一些读取/写入内部文件的示例代码

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);//Or use Log.d(line);
        }
} catch (IOException e) {
    e.printStackTrace();
}

 public void write_score(int ns) throws IOException {
    File file = new File(context.getFilesDir(), "history.txt");
    BufferedWriter w = new BufferedWriter(new FileWriter(file, true));//true makes it append
    w.write(String.valueOf(ns) + ",");
    w.close();
}

关于java - 为什么在 java 中使用 FileReader 时找不到我的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61259991/

相关文章:

Java:为什么在调用 .readObject() 时,具有引用泛型类型的 ArrayList 不计为强制转换?

java - 无法使用 <html :checkbox property ="..."> when iterating a list 访问属性

java - 在 Android 上使用 SQLDelight JVM 驱动程序

python - 如何从 Python 目录中的所有子目录中查找最近修改的文件?

java - 按顺序从 Cassandra 检索结果

java - 带有 java 编译器的客户端模板语言(DRY 模板)

Android 应用程序首次启动需要更多时间甚至 30 秒或更长时间

android - 如何在android中增加strings.xml中的字体大小

java - 如何使 File 类输入的文件名区分大小写?

java - 将文件分发到多个文件夹而不是单个文件夹的原因