Java 在Try/Catch中初始化
我在编写应用程序时遇到了一个很大的障碍。这是我的问题: 我正在尝试初始化文件输入流,如下所示:Java 在Try/Catch中初始化,java,android,Java,Android,我在编写应用程序时遇到了一个很大的障碍。这是我的问题: 我正在尝试初始化文件输入流,如下所示: FileInputStream fis fis = openFileInput(selectedFile); 然后把这一行放在后面: byte[] input = new byte[fis.available()]; 问题是两个代码位都需要try/catch语句,第二个块无法识别fis,因为它是在try/catch中初始化的。这是我的密码: private void openFile(String
FileInputStream fis
fis = openFileInput(selectedFile);
然后把这一行放在后面:
byte[] input = new byte[fis.available()];
问题是两个代码位都需要try/catch语句,第二个块无法识别fis,因为它是在try/catch中初始化的。这是我的密码:
private void openFile(String selectedFile) {
String value = "";
FileInputStream fis;
try {
fis = openFileInput(selectedFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
byte[] input = new byte[fis.available()];
} catch (IOException e) {
e.printStackTrace();
}
我该怎么办?(提前感谢)设置
FileInputStream fis=null第一次声明变量时的代码>
您也可以这样运行代码,因为IOException还将捕获文件未找到异常
String value = "";
FileInputStream fis;
try {
fis = openFileInput(selectedFile);
byte[] input = new byte[fis.available()];
} catch (IOException e) {
e.printStackTrace();
}
将FileInputStream设置为临时值null
将是最佳选项,如:
FileInputStream fis = null;
这是因为如果try语句抛出错误,那么fis将永远不会初始化。那你就有麻烦了。如果没有完全退出,还应该在try/catch块之后添加语句,测试值是否为null,这样程序就不会抛出null指针异常
所以可能是这样的:
if(fis == null) {
return; // Which will just end the method.
}
还可能希望将try/catch放在一起(您仍然应该声明try之外的其他内容,至少是您计划稍后在代码中直接使用的任何内容),但这可能更有效地进行编码),如:
在这种情况下,最好的方法是根本不捕获IOException
private void openFile(String selectedFile) throws IOException {
FileInputStream fis = openFileInput(selectedFile);
byte[] input = new byte[fis.available()];
在获得FileNotFoundException后继续将fis初始化为临时值是没有意义的(如果尝试null
,它会起作用)。问题是,这就是程序应该如何工作。在try/catch之外声明变量,或者捕获两个异常。您尝试打开文件,如果失败,您只打印堆栈跟踪,然后继续尝试。。。这将产生NPE。至少让你的openFile()
方法抛出IOException
!仅供参考-FileNotFoundException
是一个IOException
,因此您可以在一个catch(IOException e)
语句中同时捕获这两个异常。不要忘记关闭finally
块中的IO流。您还需要在第一个异常后返回,或者在第二个块中添加空检查。非常感谢!我会将您的答案标记为正确,但我还需要12分钟。我做了一些编辑,为您提供了另一种修复代码的方法。但不要忘记,您需要关闭finally块上的输入流,因此即使是这样,也应该用try/finally
包围。
private void openFile(String selectedFile) throws IOException {
FileInputStream fis = openFileInput(selectedFile);
byte[] input = new byte[fis.available()];