深入JavaIO和Google GuavaIO文件复制性能小测

来源:互联网 发布:sql 查询某个字段包含 编辑:程序博客网 时间:2024/05/21 06:39

本人菜鸟,今天写了一些IO的测试,贴出来与大家共勉,有不同看法的欢迎指出,我也会亲自测试改进,谢谢!

先贴出3个方法的代码,后面再总结下...

首先写的是java原生的IO复制代码,用FileInputStream和FileOutputStream来复制文件,代码如下:

public long testIOCopy(File in,File out) throws Exception{//986
Date begin = new Date();
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);

byte[] b = new byte[1024*50];//回根据每次读的大小,性能有所改观
fis.read(b ); //[1024] 580
fis.read(b ); //[1024*10] 150
fis.read(b ); //[1024*50] 80
int i;
while((i = fis.read(b)) != -1){
fos.write(b);
}
fos.close();
fis.close();
Date end = new Date();
return end.getTime() - begin.getTime();
}


下面也是用了javaIO,不过是用了FileChannel文件通道来实现复制,代码如下:

public long testFileChannel(File in,File out) throws Exception{//94  32
Date begin = new Date();
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);

FileChannel inChannel = fis.getChannel();
FileChannel outChannel = fos.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);

outChannel.close();
inChannel.close();
fos.close();
fis.close();
Date end = new Date();
return end.getTime() - begin.getTime();
}

最后是用Google Guava提供的Files类的copy实现,代码:

public long testGuavaIO(File in,File out) throws Exception{//2230
Date begin = new Date();
Files.copy(in, out);

Date end = new Date();
return end.getTime() - begin.getTime();
}


最后总结:我是用的一个QQ的安装文件(大小为55M多)来测试的,. 3个方法,在首次运行时,时间都相比后面运行时长,总的来说,用FileChannel时间相对比较少,在50毫秒左右,而Guava的copy用时在200-280之间,但他的代码最简洁,也不用我们来手动关闭流,后面会贴出Guava的源码,java原生的FileInputStream和FileOutputStream,在根据每次读取的字节大小,性能有所提升,上面的代码中也贴了根据每次读取大小的用时长短,

Guava的源码:

  public static void copy(File from, File to) throws IOException {
    checkArgument(!from.equals(to),
        "Source %s and destination %s must be different", from, to);
    asByteSource(from).copyTo(asByteSink(to));
  }

public long copyTo(ByteSink sink) throws IOException {
    checkNotNull(sink);
    Closer closer = Closer.create();
    try {
      InputStream in = closer.register(openStream());
      OutputStream out = closer.register(sink.openStream());
      return ByteStreams.copy(in, out);
    } catch (Throwable e) {
      throw closer.rethrow(e);
    } finally {
      closer.close();
    }
  }

以上是自己亲测,如大家还有更多更好的方法,欢迎讨论!

0 0
原创粉丝点击