2

我一直在玩弄安卓平台,玩弄不同的数据存储方式。现在我正在使用Context方法openFileInput()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不读任何东西(我不知道它是什么)。

4

1 回答 1

1

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

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

这是我的代码,我放入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!]

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

于 2013-08-16T08:44:55.387 回答