java.nio将一个文件的内容写入到另一个的文件简单例子

本文提供了一个使用Java NIO的通道进行文件复制的示例。通过ReadableByteChannel读取源文件,WritableByteChannel写入目标文件,实现了高效的数据传输过程。

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

/**
 * 将数据从一个通道复制到另一个通道或从一个文件复制到另一个文件
 * @author Administrator
 *
 */
public class ChannelDemo {
public static void main(String[] args) throws Exception {
FileInputStream in = new FileInputStream("E://PAGE.txt");
ReadableByteChannel source = in.getChannel();
FileOutputStream out = new FileOutputStream("E://User.txt");
WritableByteChannel destination = out.getChannel();
copyData(source,destination);
source.close();
destination.close();
System.out.println("success");
}


private static void copyData(ReadableByteChannel source,
WritableByteChannel destination) throws IOException {
ByteBuffer buffer = ByteBuffer.allocateDirect(20*1024);
while(source.read(buffer) != -1){
buffer.flip();
while(buffer.hasRemaining()){//剩余可用长度
destination.write(buffer);
}
buffer.clear();
}

}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值