0

在编写我的应用程序时,我遇到了相当大的障碍。这是我的问题:

我正在尝试像这样初始化文件输入流:

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();
        }

我应该怎么办?(提前致谢)

4

3 回答 3

1

在这种情况下,最好的方法是根本不捕获 IOException。

private void openFile(String selectedFile) throws IOException {
        FileInputStream fis =  openFileInput(selectedFile);
        byte[] input = new byte[fis.available()];

得到 FileNotFoundException 后继续没有意义

于 2013-06-01T01:51:18.030 回答
0

FileInputStream fis = null;首次声明变量时设置。

你也可以像这样运行你的代码,因为 IOException 也会捕获文件未找到异常。

String value = "";
FileInputStream fis;
try {
  fis = openFileInput(selectedFile);
  byte[] input = new byte[fis.available()];
} catch (IOException e) {
  e.printStackTrace();
}
于 2013-06-01T01:45:50.397 回答
0

将 FileInputStream 设置为临时值。null将是最好的选择,如:

FileInputStream fis = null;

这样做的原因是因为如果你的 try 语句抛出错误,那么我永远不会初始化 fis。那你就会有问题。如果你没有完全退出这个东西,你还应该在 try/catch 块之后添加语句来测试值是否为空,这样程序就不会抛出空指针异常。

所以也许是这样的:

if(fis == null) {
    return; // Which will just end the method.
}

也可能想把 try/catch 放在一起(你仍然应该在 try 之外声明其他东西,至少是你打算稍后在代码中直接使用的任何东西),但它可能更有效地编码),如:

FileInputStream fis = null;
byte[] input = null;
try {
    fis = openFileInput(selectedFile);
    input = new byte[fis.available()];
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
于 2013-06-01T01:49:50.543 回答