为什么要使用finally关闭对象?

感觉finally会让代码变得很难看,如果不用,会带来什么后果

下面是代码,f1比f2清爽了不少

    public static void f1(File in, File out) throws IOException {
        FileChannel inChannel = new FileInputStream(in).getChannel();
        FileChannel outChannel = new FileOutputStream(out).getChannel();
        int maxCount = (64 * 1024 * 1024) - (32 * 1024);
        long size = inChannel.size();
        long position = 0;
        while (position < size) {
            position += inChannel.transferTo(position, maxCount, outChannel);
        }
        if (inChannel != null) inChannel.close();
        if (outChannel != null) outChannel.close();
    }

    public static void f2(File in, File out) throws IOException {
        FileChannel inChannel = new FileInputStream(in).getChannel();
        FileChannel outChannel = new FileOutputStream(out).getChannel();
        try {
            int maxCount = (64 * 1024 * 1024) - (32 * 1024);
            long size = inChannel.size();
            long position = 0;
            while (position < size) {
                position += inChannel.transferTo(position, maxCount, outChannel);
            }
        } finally {
            if (inChannel != null) {
                inChannel.close();
            }
            if (outChannel != null) {
                outChannel.close();
            }
        }
    }

finally就是防止在出现io异常时,流关闭不上的事情,每个操作系统都有个最大的打开文件数,超过的话,系统就会崩溃;
当然了sql也是一样的,只要是资源,在jdk之前都只能用finally;

在jdk1.7之后,有一个更优雅的实现方式,但是也是有try..catch语句块的,只是没有了finally
如:
try (InputStream in = new FileInputStream("your file name")) {
//正常业务处理
} catch(Exception e) {
//异常处理
}
在语句执行完后,会自动调用in的close方法进行关闭;

资源是一个很严谨的东西,所以一定要把它当成大事来对待;否者程序的可用性会大大降低;

希望对你有所帮助...

finnaly的好处就是不管try正常执行完,或者有异常被catch,最后都会调用finally,这样就等于有一个统一的地方来进行清理,处理工作。不需要考虑各种代码分支

这些IO操作就像你灭火的时候要用到消防水管,打开消防水管后就能用到水。正常情况下是你用完水就将其关闭。假如你遇到了异常比如消防员昏倒了(当然现实中不可能),
这时候水就没人去关闭,会造成水资源的浪费。
IO流中的操作也是一个道理,在使用IO流的时候就要考虑到异常情况。一旦出现异常情况,流将无法正常关闭。所以必须在finally块中去强行关闭。

就是关闭资源的 不然一直开着 很占用资源的 尤其是大量访问量时候 这是致命的

首先,你要知道finally的作用是什么?
finally的作用是无论你前面是否发生抛出异常,都会执行它里面的语句。
然后,如果你不关闭资源,会很浪费资源的,这样会存在很多漏洞,慢慢积累多了,就会崩掉,很危险。
所以呢,我们常常在finally中设置关闭资源。确保程序的稳定性、可靠性。

 try{
 // 打开资源比如文件流
 // 处理文件流
 // 异常了,跳到异常处理,这个时候没有关闭文件流
 // 如果在这里写关闭文件流,再上面抛异常后,走不到这句
}
catch(exception e)
{
}
finally{
// 关闭文件流   不管有没有异常,最后都走finally ,所以用finally来释放资源代码一定会走到,最好不过了
}

那你说不用finally,那就是是在try和catch里面都要写一次关闭的代码,因为你正常执行代码,就不会执行到cath里面,所以try里面要关闭一次,如果代码错误,就可能不会执行try里面的关闭,跳到catch里面了,但连接必须关闭,所以在catch里面也要写一次,这样就造成代码冗余了。

拿你这个例子来说,方法f1中的:
FileChannel inChannel = new FileInputStream(in).getChannel();
FileChannel outChannel = new FileOutputStream(out).getChannel();
如果抛出异常,程序不执行后面关闭的语句
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
你的channel就关闭不了了,但是用finally包裹,channel的关闭语句都会被执行到

最主要的就是防止资源泄漏等情况