如何使用Java NIO复制文件?
以下代码段显示了如何使用NIOAPI复制文件。的NIO(新IO)API是在java.nio.*包。它至少需要Java1.4,因为此版本中首先包含了API。JAVANIO是基于块的IO处理,而不是基于流的IO,后者是Java中的旧版本IO处理。
package org.nhooo.example.io;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
public class CopyFileExample {
public static void main(String[] args) throws Exception {
String source = "medical-report.txt";
String destination = "medical-report-final.txt";
FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(destination);
FileChannel inputChannel = fis.getChannel();
FileChannel outputChannel = fos.getChannel();
// 创建一个1024大小的缓冲区以缓冲数据
// 从源文件复制到目标文件时。
// 为了在这里创建缓冲区,我们使用了静态方法
// ByteBuffer.allocate()
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 在这里,我们开始读取源文件并将其写入
//到目标文件。我们重复这个过程
// 直到输入流通道的read方法返回
// 没有(-1)。
while (true) {
// 读取数据块并将其放入缓冲区
int read = inputChannel.read(buffer);
//我们到达通道尽头了吗?如果是
// 跳出while循环
if (read == -1) {
break;
}
// 翻转缓冲区
buffer.flip();
// 写入目标通道并清除缓冲区。
outputChannel.write(buffer);
buffer.clear();
}
}
}