openFileInput() and/or openFileOutput() i/o streams silently failing

前端 未结 1 1760
难免孤独
难免孤独 2021-01-22 20:57

I\'ve been fooling around with the android platform, messing around with different ways of storing data. Right now I am using the Context methods openFileInpu

相关标签:
1条回答
  • 2021-01-22 21:30

    I write back as answer, because this is getting too much for a comment. I've tried your code - and well, it just works fine.

    The only thing I can imagine is, that your device has a problem. In which case I would expect some exception...
    What you still can do, is to copy my code and check the log. See if it works, or if you might get some exception. Then check how much internal memory you got in your device (is it real or emulated?)
    If it is emulated it might be too small for even such a small file.

    Here's my code, that I put into 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);
        }
    

    The output:

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

    Is there a category of: "Helpful, but not sovling the problem"?

    0 讨论(0)
提交回复
热议问题