当前位置 : 主页 > 编程语言 > c++ >

NIO利用文件流复制文件

来源:互联网 收集:自由互联 发布时间:2021-07-03
NIO与文件流合作复制文件 public static void nioCopyFile(String resource, String destination) throws IOException { FileInputStream fis = new FileInputStream(resource); FileOutputStream fos = new FileOutputStream(destination); FileCh
NIO与文件流合作复制文件
public static void nioCopyFile(String resource, String destination)
            throws IOException {
        FileInputStream fis = new FileInputStream(resource);
        FileOutputStream fos = new FileOutputStream(destination);
        FileChannel readChannel = fis.getChannel(); //读文件通道
        FileChannel writeChannel = fos.getChannel(); //写文件通道
        ByteBuffer buffer = ByteBuffer.allocate(1024); //读入数据缓存
        while (true) {
            buffer.clear();
            int len = readChannel.read(buffer); //读入数据
            if (len == -1) {
                break;
//读取完毕
            }
            buffer.flip();
            writeChannel.write(buffer);
//写入文件
        }
        readChannel.close();
        writeChannel.close();
    }
网友评论