1

我想在我的内部存储中保存一个文件,然后经过一些处理以使用 RandomAccessFile 打开它,当我尝试打开该文件时,它会抛出异常 FileNotFound ...我哪里出错了?

FileOutputStream fos = getApplicationContext().openFileOutput("xxx.txt", Context.MODE_PRIVATE);

RandomAccessFile access = new RandomAccessFile("xxx.txt", "r");

4

2 回答 2

2

If you create a file and write to it, you have to close() it before re-opening.

In addition, at least on some devices the file by default goes to the root directory.

public void test() {
    try {
        RandomAccessFile access = new RandomAccessFile(new File(getFilesDir(),"xxx.txt"), "rw");
        access.writeBytes("hello");
        access.close();
    } catch (IOException x) {
        x.printStackTrace();
    }
}
于 2013-08-08T12:59:13.253 回答
1

这很可能是因为您通过以下方式写入文件:

FileOutputStream fos = getApplicationContext().openFileOutput("xxx.txt", Context.MODE_PRIVATE);

但是然后您尝试在默认目录中打开一个文件:

RandomAccessFile access = new RandomAccessFile("xxx.txt", "r");

这与之前使用的输出目录不同。

因此,您可以获取openFileOutput()with使用的目录getFileStreamPath (String name),因此请使用以下内容创建您的目录RandomAccessFile

RandomAccessFile access = new RandomAccessFile(getFileStreamPath("xxx.txt"), "r");
于 2013-08-08T14:08:45.420 回答