转载:java 7新特性-TWR(Try-with-resources)

原始链接:https://blog.csdn.net/ty_laurel/article/details/60348495

java 7新特性-TWR(Try-with-resources)


今天在资料上练习文件拷贝程序时,遇到了java 7中的一个新特性TWR,可以减少实际中的部分代码书写,对其做以记录。

try-with-resources语句是声明了一个或多个资源的try语句块。在java中资源作为一个对象,在程序完成后必须关闭。try-with-resources语句确保每个资源在语句结束时关闭。只要是实现了java.lang.AutoCloseable的任何对象(包括实现java.lang.Closeable的所有对象)都可以使用该方式对资源进行关闭。

在java 7之前,一般在进行文件IO操作时都需要显式的进行文件流(也可以理解为资源)的close操作,无论是操作到文件流末尾还是发生异常。往往很简单的一个逻辑都要好几行的代码进行修饰,使得代码结构变的复杂。如下例子,不管try语句块正常结束还是发生异常,都可以使用finally语句块来确保资源被关闭:

static String ReadFile(String file) throws IOException {
  BufferedReader br = new BufferedReader(new FileReader(file));
  try {
    return br.readLine();
  } finally {
    if (br != null) 
         br.close();
  }
}
对于以上语句块,改写为TWR时,如下:


static String ReadFile(String file) throws IOException {
  try(BufferedReader br = new BufferedReader(new FileReader(file))) {
    return br.readLine();
  }
}
可以很明显看出代码的精简。


上边说过,只要是实现了AutoCloseable和Closeable接口的的对象都可以使用该方式,看下上例子中的BufferedReader类的源码实现:


    public class BufferedReader extends Reader {
其继承了Reader抽象类,继续往上查看Reader抽象类,确实实现了Closeable:

    public abstract class Reader implements Readable, Closeable {

明白了TWR具体含义,实例运用下,实现文件拷贝实现,代码中采用了两种方式实现文件拷贝过程(普通方式和NIO方式),两者存在一些性能的差异,感兴趣的读者可以自己测试代码性能。
package javaFile.copyfile;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
 
public final class CopyFile {     //使用final定义工具类,不用实例化
    private CopyFile() {   //若实例化,则报错
        throw new AssertionError();
    }
    
    public static void fileCopy(String source, String target) throws IOException {
        try(InputStream in = new FileInputStream(source)) {
            try(OutputStream out = new FileOutputStream(target)){
                byte[] buffer = new byte[4096];
                int bytesToRead;
                while((bytesToRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesToRead);
                }
            }
        }
    }
    
    public static void fileCopyNIO(String source, String target) throws IOException {
        try(FileInputStream in = new FileInputStream(source)) {
            try(FileOutputStream out = new FileOutputStream(target)) {
                FileChannel inChannel = in.getChannel();
                FileChannel outChannel = out.getChannel();
                ByteBuffer buffer = ByteBuffer.allocate(4096);  //申请4096字节缓冲
                while(inChannel.read(buffer) != -1) {
                    buffer.flip();   //反转此缓冲区,设置当前位置指针为0,read读文件后文件指针在缓冲区末尾,需要使用flip重置
                    outChannel.write(buffer);
                    buffer.clear();   //清空缓冲区
                }
            }
        }
    }
    
    public static void main(String[] args) throws IOException {
        //CopyFile copyfile = new CopyFile();
        long start = System.currentTimeMillis();
        CopyFile.fileCopyNIO("E:\\大数据.rar", "E:\\testtest");
        long end = System.currentTimeMillis();
        System.out.println("耗时:"+(end-start));
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值