利用NIO复制文本内容到另一个文本中

本文提供了一个使用Java进行文件复制的示例代码。通过创建输入输出流并利用管道进行数据传输,实现从一个文件到另一个文件的数据复制。该示例展示了如何使用ByteBuffer进行数据的读取和写入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static void main(String args[]) throws IOException {
        //获取当前项目路径
        String relativelyPath = System.getProperty("user.dir");
        System.out.println(relativelyPath);
        //创建输入流
        FileInputStream input = new FileInputStream(relativelyPath + "/in.txt");
        //创建读取管道
        ReadableByteChannel source = input.getChannel();
        //创建输出流
        FileOutputStream output = new FileOutputStream(relativelyPath + "/out.txt");
        //创建写入管道
        WritableByteChannel destination = output.getChannel();
        //复制数据
        copyData(source, destination);
        source.close();
        destination.close();
        System.out.println("复制文本内容数据成功!");
    }

    private static void copyData(ReadableByteChannel src, WritableByteChannel dest) throws IOException {
        //定义缓冲区容量
        ByteBuffer buffer = ByteBuffer.allocateDirect(20 * 1024);
        while (src.read(buffer) != -1) {
            // 调换这个buffer的当前位置,并且设置当前位置是0。说的意思就是:将缓存字节数组的指针设置为数组的开始序列即数组下标0。这样就可以从buffer开头,对该buffer进行遍历(读取)了。
            buffer.flip();
            //判断缓冲区是否还有数据
            while (buffer.hasRemaining()) {
                dest.write(buffer);
            }
            //将数据写入输出文件
            buffer.clear();
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值