0

I am trying to get a simple Hello World txt file to be written then read by my android application. When viewing the DDMS File Explorer it successfully creates the text file but i then get a FileNotFoundException when trying to read it.

try {

        final String TESTSTRING = new String("Hello World");

        FileOutputStream fOut = openFileOutput("test.txt", MODE_WORLD_READABLE);
        OutputStreamWriter osw = new OutputStreamWriter(fOut);

        osw.write(TESTSTRING);
        osw.flush();
        osw.close();

        FileInputStream fIn = new FileInputStream("test.txt");
        InputStreamReader isr = new InputStreamReader(fIn);

        char[] inputBuffer = new char[TESTSTRING.length()];

        isr.read(inputBuffer);

        String readString = new String(inputBuffer);

        boolean isTheSame = TESTSTRING.equals(readString);

        Log.i("File Reading Stuff", "success = " + isTheSame);

    } catch (IOException e) {
        e.printStackTrace();
    }

also the error is java.io FileNotFoundException: /test.txt (No such file or directory)

Any Help Thanks.

2 Answers2

2

I don't know where openFileOutput saves its files, but wouldn't you use it's input equivalent openFileInput to read such a file?

Nanne
  • 64,065
  • 16
  • 119
  • 163
  • `openFileOutput()` saves its files in the directory identified by `getFilesDir()`. The OP should either use `openFileInput()` as you suggest or use `getFilesDir()` to construct a valid `File` object to the right spot to be able to use `FileInputStream` directly. – CommonsWare Apr 16 '11 at 19:24
0

See my previous post with information about how to read/write to the external storage directory in Android:

Android how to use Environment.getExternalStorageDirectory()

-- Dan

Community
  • 1
  • 1
debracey
  • 6,517
  • 1
  • 30
  • 56
  • I attempted to use the virtual sd card but I keep getting `java.io.FileNotFoundException: /mnt/sdcard/sdTest.txt (Permission denied)` – Kyle Bartz Apr 16 '11 at 20:28
  • You need to add permissions to write the SD card in your application's manifest - specifically: WRITE_EXTERNAL_STORAGE. If you're not going to do any writing, then you need to open your file read only – debracey Apr 19 '11 at 00:58