package com.roc.nio;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* 利用NIO进行文件读取的一般步骤:
* 1:新建一个File对象
* 2:利用FileInputStream 内部的getChannel方法获取到这个file的通道
* 3:新建一个适合大小的Buffer来容纳这些文件中的数据
* 4:调用channel.read(buffer)的方法写入buffer中
* @author lenovo
*
*/
public class FileNio {
@SuppressWarnings("resource")
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
File file = new File("build.gradle");
File bak = new File("build.gradle.bak");
FileInputStream fileInputStream = new FileInputStream(file);
FileOutputStream bakOutputStream = new FileOutputStream(bak);
FileChannel fileChannel = fileInputStream.getChannel();
FileChannel bakChannel = bakOutputStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(10);
while(true) {
/**
* 如果不调用clear方法,buffer的position和limit的位置是一样的,
* 这样会导致fileChannel的read方法会返回0,不仅文件中的其他内容无法写入buffer,
* 源码细节(https://blog.csdn.net/u013828625/article/details/79699743)
* 而且当前应用就会进入死循环
*/
buffer.clear();
int sta = fileChannel.read(buffer);
if(sta == -1) {
break;
}
/**
* 一定要记得调用flip方法,调整limit=position,positon=0,这样才能将buffer中的数据拿出来
*/
buffer.flip();
bakChannel.write(buffer);
}
fileInputStream.close();
bakOutputStream.close();
}
}
使用FileChannel实现文件的操作
最新推荐文章于 2023-04-18 09:06:23 发布