Andi Jay Andi Jay - 1 month ago 14
Android Question

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 guide 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?

Answer

Replace

FileOutputStream fos;

with

FileOutputStream fos = null;
Comments