views:

45

answers:

2

I'm trying to run this piece of code inside my onCreate method as an initial test into writing private data for my app to use. This code is straight out of the Android SDK development guide located here (http://developer.android.com/guide/topics/data/data-storage.html#filesInternal)

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

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

However, this code give me errors for the 3 lines of code at the bottom. The error is an unhanded exception. The suggested quick fix is do to the following:

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

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

But after doing that I get an error for the bottom two lines which states that fos may not be uninitialized. How can I fix this code? It's kind of annoying that the Android SDK gives you an example that doesn't even work.

I can't say I'm an expert at exception handling either.

+1  A: 

Replace

FileOutputStream fos;

with

FileOutputStream fos = null;
cement
I see, that worked. Perhaps it's time for me to finally start learning about exceptions in java :)
CrazyJay
A: 

Yes, the problem here is that if you get a FileNotFoundException you try to just print out the exception and continue, but in that case, the fos variable would have never been assigned a value, since the "openFileOutput" call wouldn't have completed. This is fine, because in the case when you weren't able to open a file, you don't want to continue to try to write to the file you didn't open.

Since a FileNotFoundException IS a IOException, you could simplify all of this as:

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

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

In this case, the first thing that raises an exception causes the stack trace to get printed, and you skip any subsequent operations in the rest of the try {} block.

The problem with cement's answer is that, although it gets by the compiler error, if the first block ever throws the exception, the second block will give you a NullPointerException.

stew