FileChannel 文件通道
程序员文章站
2022-04-24 13:36:59
...
FileChannel是专门操作文件通道,通过FileChannel,即可以从一个文件读取数据,也可以将数据写入文件中。 FileChannel为阻塞模式,不能设置为非阻塞模式
FileChannel文成文件复制的实战案例。具体的功能使用FileChannel将原文件 复制一份,把原文件的数据都复制到目标文件中:
/**
* NIO FileChannel 复制文件
*
* @param srcPath
* @param destPath
*/
@SneakyThrows
public static void nicCopyFile(String srcPath, String destPath) {
File srcFile = new File(srcPath);
File destFile = new File(destPath);
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
//输入通道
FileChannel inputStreamChannel = null;
//输出通道
FileChannel outputStreamChannel = null;
long timeMillis = 0;
try {
if (!destFile.exists()) {
destFile.createNewFile();
}
timeMillis = System.currentTimeMillis();
fileInputStream = new FileInputStream(srcFile);
fileOutputStream = new FileOutputStream(destFile);
inputStreamChannel = fileInputStream.getChannel();
outputStreamChannel = fileOutputStream.getChannel();
int length = -1;
ByteBuffer buffer = ByteBuffer.allocate(1024);
while ((length = inputStreamChannel.read(buffer)) != -1) {
//buffer第一次模式切换:翻转buf,从写模式变成读模式
buffer.flip();
int outLength = 0;
// 将buffer写入输出的通道
while ((outLength = outputStreamChannel.read(buffer)) != 0) {
System.out.printf("写入的字节数:" + outLength);
}
//buf 第二次模式切换: 清楚buffer,变成写模式
buffer.clear();
}
//强制刷新到磁盘
outputStreamChannel.force(true);
} catch (IOException e) {
e.printStackTrace();
} finally {
fileInputStream.close();
fileOutputStream.close();
inputStreamChannel.close();
outputStreamChannel.close();
long currentTimeMillis = System.currentTimeMillis();
log.info("base复制毫米数", currentTimeMillis - timeMillis);
}
}
}