开发者

Error: FileOutputStream may not be initialized

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 gui开发者_如何学编程de located here

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 unhandled 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 initialized. How can I fix this code?


Replace

FileOutputStream fos;

with

FileOutputStream fos = null;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜