在Java中处理IO异常

fre*_*low 14 java io exception-handling exception resource-management

基本上,我想打开一个文件,读取一些字节,然后关闭该文件.这就是我想出的:

try
{
    InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
    try
    {
        // ...
        inputStream.read(buffer);
        // ...
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally
    {
        try
        {
            inputStream.close();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
catch (FileNotFoundException e)
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

也许我被RAII宠坏了,但是必须有更好的方法在Java中做到这一点,对吗?

vit*_*aut 12

如果你有相同的异常处理代码IOException,FileNotFoundException那么你可以用一个只有一个catch子句的更紧凑的方式重写你的例子:

try {
    InputStream input = new BufferedInputStream(new FileInputStream(file));
    try {
        // ...
        input.read(buffer);
        // ...
    }
    finally {
        input.close();
    }
}
catch (IOException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

try-catch如果可以传播异常,甚至手动打印堆栈跟踪可能更有意义,您甚至可以摆脱外部.如果您没有在程序中发现异常,则会自动为您打印堆栈跟踪.

此外,手动关闭流的需求将在Java 7中通过自动资源管理来解决.

通过自动资源管理和异常传播,代码简化为以下内容:

try (InputStream input = new BufferedInputStream(new FileInputStream(file))) {
    // ...
    input.read(buffer);
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 因此,在其第一版发布约15年后的第7版中,Java最终将(没有双关语意图)提供其创建的语言的一个主要特性以进行改进.我印象不深. (4认同)