美文网首页
文件copy

文件copy

作者: 装完逼立马跑 | 来源:发表于2018-04-11 19:03 被阅读0次

IO流:

public static void fileCopy(String source,String target) throws IOException {
        Long beginTime = System.nanoTime();
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(source);
            out = new FileOutputStream(target);
            int total;
            byte[] buff = new byte[1024];
            while ((total = in.read(buff)) != -1) {
                out.write(buff, 0, total);
            }
        }finally {
            in.close();
            out.close();
            Long endTime = System.nanoTime();
            System.out.println(" IO时长:"+(endTime-beginTime)+"纳秒");
        }
    }

NIO

public static void fileCopyNio(String source ,String target) throws IOException {
        Long beginTime = System.nanoTime();
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            inChannel = new FileInputStream(source).getChannel();
            outChannel = new FileOutputStream(target).getChannel();
            ByteBuffer buff = ByteBuffer.allocate(1024);
            while(inChannel.read(buff) != -1){
                buff.flip();
                outChannel.write(buff);
                buff.clear();
            }
            //这个也可以
//            outChannel.transferFrom(inChannel, 0 , inChannel.size());
        }finally {
            inChannel.close();
            outChannel.close();
            Long endTime = System.nanoTime();
            System.out.println("NIO时长:"+(endTime - beginTime)+"纳秒");
        }
    }

发现小文件测试的时候io速度更快...而大文件是nio更快

相关文章

网友评论

      本文标题:文件copy

      本文链接:https://www.haomeiwen.com/subject/fzvzhftx.html