2

I'm so confused. After reading this thread, I'm trying to write a List to internal storage onPause(), then read the List onResume(). Just for testing purposes, I'm trying to write a simple string as the example showed. I've got this to write with:

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

    FileOutputStream fos = null;
    try {
        fos = openFileOutput(FILENAME, Context. MODE_WORLD_READABLE);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        fos.write(string.getBytes());
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        fos.close();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

And I'm trying to read it in onResume() by calling:

    try {
            resultText01.setText(readFile("hello_file"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            resultText01.setText("exception, what went wrong? why doesn't this text say hello world!?");
        }

Which of course uses this:

private static String readFile(String path) throws IOException {
      FileInputStream stream = new FileInputStream(new File(path));
      try {
        FileChannel fc = stream.getChannel();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        /* Instead of using default, pass in a decoder. */
        return Charset.defaultCharset().decode(bb).toString();
      }
      finally {
        stream.close();
      }
    }

For some reason, resultText01.setText(...) isn't being set to "hello world!", and is instead calling the catch exception. I'm sorry if my lingo isn't correct, I'm new to this. Thanks for any pointers.

Community
  • 1
  • 1
ajwest
  • 258
  • 7
  • 17

1 Answers1

2

Instead of the following in your readFile(...) method...

FileInputStream stream = new FileInputStream(new File(path));

Try...

FileInputStream stream = openFileInput(path);
Squonk
  • 48,735
  • 19
  • 103
  • 135
  • You're awesome! I also had to remove the `static` from the `readFile()` method. Works well now though. (Plus I don't really know what the difference between static and non-static stuff is, so I just put them in and remove them randomly whenever I see eclipse yell at me.) – ajwest Jun 25 '11 at 22:36
  • @Age: Glad to help. I hadn't spotted the `static` declaration but it might have been relevant anyway depending on the rest of your code. As a rule of thumb, don't use it unless you're sure it's needed. Try Google for 'Java static keyword' - it might bring up some stuff which will help understanding it. – Squonk Jun 25 '11 at 23:25