Java中文件复制的一个汇总

Java文件复制(包括NIO)

我们首先定义一个拷贝接口:

public interface FileCopyRunner {
    void copyFile(File source, File target) throws IOException;
}

最原始的复制方法(不涉及到缓存)

FileCopyRunner noBufferStreamCopy = (source, target) -> {
            int r;
            InputStream fin = null;
            OutputStream fout = null;

            try {
                fin = new FileInputStream(source);
                fout = new FileOutputStream(target);
                while ((r = fin.read()) != -1){
                    fout.write(r);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                close(fin);
                close(fout);
            }
        };

上面是直接从源文件中读取出来,然后写入目标文件中。


基于缓存的文件复制方式

FileCopyRunner bufferedStreamCp = (source, target) -> {
            InputStream fin;
            OutputStream fout;
            fin = new BufferedInputStream(new FileInputStream(source));
            fout = new BufferedOutputStream(new FileOutputStream(target));
            byte[] buffer = new byte[1024];
            int r ;
            while((r = fin.read(buffer)) != -1){
                fout.write(buffer,0,r);
            }
            close(fin);
            close(fout);
        };

上面我们定义了一个1024字节的buffer,每次读取这么一个大小放入缓存中,然后一次性写入文件中。


NIO方式复制

FileCopyRunner nioBufferCopy = (source, target) -> {
            FileChannel fin;
            FileChannel fout;

            fin = new FileInputStream(source).getChannel();
            fout = new FileOutputStream(target).getChannel();

            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while(fin.read(buffer) != -1){
                buffer.flip();
                while(buffer.hasRemaining()) fout.write(buffer);
                buffer.clear();
            }

            close(fin);
            close(fout);
        };

上面的似乎有些复杂,下面是简化版。


简化版NIO

FileCopyRunner nioTransferCopy = (source, target) -> {
            FileChannel fin = null;
            FileChannel fout = null;
            fin = new FileInputStream(source).getChannel();
            fout = new FileOutputStream(target).getChannel();
            long len = 0L;
            while (len != fin.size()) {
                len += fin.transferTo(0,fin.size(),fout);
            }
            close(fin);
            close(fout);
        };

下面是关闭流close函数的一个定义:

public static void close(Closeable closeable) throws IOException {
        if(closeable != null) closeable.close();
    }

你可能感兴趣的:(Java开发日记,计算机网络,大厂面试算法指南)