我想从我创建的方法返回 String 类型的数据。 Eclipse 说需要在 try catch block 之后指定一个返回类型...当我这样做时,Eclipse 然后告诉我需要将 String 数据声明为局部变量...这里出了什么问题?
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;
}
最佳答案
您在 try
block 中声明 data
。它超出了该 block 之外的范围。
您可以只需将声明移动到try
block 之前 - 但我个人认为删除catch
可能更有意义完全阻塞,并声明该方法可以抛出IOException
。您还应该关闭 finally
block 中的 FileInputStream
和 InputStreamReader
,这样在抛出异常时就不会让它们保持打开状态。
关于try/catch 后的 Java 返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10977569/