文件copy

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)+"納秒");
        }
    }

發(fā)現小文件測試的時候io速度更快...而大文件是nio更快

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容