还在用循环吗?Java复制文件内容NIO版本

本文介绍如何使用Java NIO进行文件复制,通过FileChannel的transferFrom和transferTo方法实现高效的数据传输。示例代码展示了从一个文件读取数据并写入另一个文件的全过程。

网上的文件操作目前都停留在老的IO API当中,这大概就是为什么NIO(New IO)都已经不new了,在中国吃透的人还是很少的缘故吧?

 

不要用循环了,来用NIO吧,只要你的JDK在1.5以上,Follow Me!

 

我们用到的是FileChannel中的2个方法

 

transferFrom(ReadableByteChannel src, long position, long count)

transferTo( long position, long count, WritableByteChannel dest)

 

这2个方法,其实都一样,就是源和目标换一下而已

 

package com.eric.thinking.java.nio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

public class TansformExample {
	public static void main(String[] args) throws IOException {
		RandomAccessFile fromFile = new RandomAccessFile("data/nio-data.txt",
				"rw");
		FileChannel fromChannel = fromFile.getChannel();

		RandomAccessFile toFile = new RandomAccessFile("data/nio-to.txt", "rw");
		FileChannel toChannel = toFile.getChannel();

		long position = 0;
		long count = fromChannel.size();

		toChannel.transferFrom(fromChannel, position, count);

		fromFile.close();
		toFile.close();
	}
}

 

简单吧?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值