I want to return data of type String from my method i created. Eclipse says need to specifiy a return type after the try catch block… When I do that, Eclipse then tells me that I need to declare String data as a Local variable… What is going wrong here?
private String ReadData() {
try {
FileInputStream fis = null;
InputStreamReader isr = null;
String data = null;
fis = KVOContact.this.openFileInput("data.txt");
isr = new InputStreamReader(fis);
char[] inputBuffer = new char[fis.available()];
isr.read(inputBuffer);
data = new String(inputBuffer);
isr.close();
fis.close();
} catch (IOException ioe) {
Log.e("KVOContact", "IOError" + ioe);
}
return data;
}
You’re declaring
datawithin thetryblock. It’s out of scope outside that block.You could just move the declaration to before the
tryblock – but personally I think it would probably make more sense to remove thecatchblock entirely, and declare that the method can throwIOException. You should also close yourFileInputStreamandInputStreamReaderinfinallyblocks so that you don’t leave them open if an exception is thrown.