nio/io 拷貝文件

nio的拷貝文件大概能比io拷貝文件快1倍左右,爲什麼會快1倍了,查看了它的源碼,發現它用到了直接內存,即與jvm內存相比,省去了一次拷貝。因此能加快速度,但它也是一把雙刃劍,有以下缺點,能夠不借用cpu,是獨立的處理器,專門用於處理iojava

①,申請內存空間比較慢jvm

②,直接內存不屬於jvm管理範圍內,釋放比較難,可能會形成oom問題,出現問題比較難排查ui

import java.io.*;
import java.nio.channels.FileChannel;

/**
 * @author hui
 * @date 2019/6/12
 */
public class IOUtil {

    public static void fileCopyWithFileChannel( FileInputStream fileInputStream,FileOutputStream fileOutputStream) {
        FileChannel fileChannelInput = null;
        FileChannel fileChannelOutput = null;
        try {
            // 獲得fileInputStream的文件通道
            fileChannelInput = fileInputStream.getChannel();
            // 獲得fileOutputStream的文件通道
            fileChannelOutput = fileOutputStream.getChannel();
            // 將fileChannelInput通道的數據,寫入到fileChannelOutput通道
            fileChannelInput.transferTo(0, fileChannelInput.size(), fileChannelOutput);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 用filechannel進行文件複製
     *
     * @param fromFile
     *            源文件
     * @param toFile
     *            目標文件
     */
    public static void fileCopyWithFileChannel(File fromFile, File toFile) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream=new FileInputStream(fromFile);
            fileOutputStream=new FileOutputStream(toFile);
            fileCopyWithFileChannel(fileInputStream, fileOutputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            IOUtil.close(fileOutputStream);
            IOUtil.close(fileInputStream);
        }

    }

  public static long copy(final InputStream input, final OutputStream output)
            throws IOException {
        byte[] buffer = new byte[1024];
        long count = 0;
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }

    public static void close(Closeable closeable){
        if(closeable != null){
            try {
                closeable.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
        }
    }

}

普通的流的拷貝.net

 

參考:http://www.javashuo.com/article/p-dhnpvfdj-mc.htmlcode

相關文章
相關標籤/搜索