CSDNRGY 2017-02-22 04:35 采纳率: 87.5%
浏览 2657
已采纳

为什么要使用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();
            }
        }
    }
  • 写回答

9条回答 默认 最新

  • little_how 2017-02-22 06:02
    关注

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

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

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

    希望对你有所帮助...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序