NIO文件读写操作

本文详细介绍如何使用Java NIO进行文件的读取与写入操作。通过具体步骤讲解,包括获取输入输出通道、创建缓冲区、从缓冲区读取或写入字节流等,帮助读者理解NIO的基本原理及其实现过程。

/**
* 使用NIO读写文件
* 1、根据输入输出流获取相应的通道
* 2、创建缓冲区
* 3、从缓冲区读出或者写入字节流到相应的通道
* @throws Exception
*/
public void oprateFileByNio() throws Exception {

long beginTime = System.currentTimeMillis();

FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(copyFile);

FileChannel inChannel = fis.getChannel(); //获取输入通道
FileChannel outChannel = fos.getChannel(); //获取输出通道

ByteBuffer mByteBuffer = ByteBuffer.allocate(1024); //分配缓冲区大小

while (true) {

mByteBuffer.clear(); //清除操作:将position设置为0,limit(限制)设置为capasity(容量)的大小

int r = inChannel.read(mByteBuffer); //将字节流从该通道读入缓冲区

//r=-1时代表已经到达流的末尾
if (r == -1) {
break;
}

mByteBuffer.flip(); //反转操作:将limit设置为当前的position,再将position设置为0

outChannel.write(mByteBuffer); //将缓冲区中字节流写入该通道

}

inChannel.close();
outChannel.close();
fis.close();
fos.close();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值