openFileInput() 和/或 openFileOutput() I/O 流默默失败

2023-12-02

我一直在研究 android 平台,研究不同的数据存储方式。现在我正在使用Context方法openFileInput() and openFileOutput().

正如这两种方法的文档告诉我的那样,我创建了一个名为 default 的文件。这是一些示例代码(这些示例是我所做的复制品,我知道文件名和变量的命名不同):

打开文件输出()...

    Context cont = /* defined somewhere */;
    String FILENAME = "hello_file";
    String string = "hello world!";

    FileOutputStream fos = cont.openFileOutput(FILENAME, Context.MODE_PRIVATE);
    fos.write(string.getBytes());
    fos.flush();
    fos.close();

打开文件输入()...

    FileInputStream fis = cont.openFileInput("hello_file");

    byte[] buffer = new byte[(int) fis.getChannel().size()];
    fis.read(buffer);
    String str= "";
    for(byte b:buffer) str+=(char)b;

    fis.close();

在这些代码片段中,“hello world”应该写入文件“hello_file”,并且应该是str。我的代码遇到的问题是,无论我向文件中写入什么内容,FileInputReader什么也没捡到。

我滚动浏览了 android 文档中列出的权限,但我找不到任何有关内部存储的信息(而且我很确定您不需要此类权限)。

最重要的是,我不明白为什么FileInputWriter没有写任何东西或者为什么FileInputReader当代码运行良好并且没有错误时,没有读取任何内容(我不知道它是什么)。


我写回答案,因为这对于评论来说太多了。 我已经尝试过你的代码 - 嗯,它工作得很好。

我唯一能想象的是,您的设备有问题。在这种情况下,我预计会有一些例外......
您仍然可以做的就是复制我的代码并检查日志。看看它是否有效,或者是否可能会出现一些异常。然后检查您的设备有多少内存(是真实的还是模拟的?)
如果是模拟的,即使是这么小的文件,它也可能太小。

这是我放入的代码onResume()

    String FILENAME = "hello_file";
    String string = "hello world!";

    try {
        FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
        fos.write(string.getBytes());
        fos.flush();
        fos.close();
    } catch (IOException e) {
        Log.e("STACKOVERFLOW", e.getMessage(), e);
    }

    try {
        FileInputStream fis = openFileInput("hello_file");
        byte[] buffer = new byte[(int) fis.getChannel().size()];
        fis.read(buffer);
        String str= "";
        for(byte b:buffer) str+=(char)b;
        fis.close();
        Log.i("STACKOVERFLOW", String.format("GOT: [%s]", str));
    } catch (IOException e) {
        Log.e("STACKOVERFLOW", e.getMessage(), e);
    }

输出:

08-16 08:31:38.748: I/STACKOVERFLOW(915): GOT: [hello world!]

是否有一个类别:“有帮助,但不能解决问题”?

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

openFileInput() 和/或 openFileOutput() I/O 流默默失败 的相关文章

随机推荐