代码如下
package com.prometheus.en;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
public class NioFileCopyUtil {
public static void copyFileByChannel(File source, File dest) throws IOException {
try (FileInputStream in = new FileInputStream(source);
FileOutputStream out = new FileOutputStream(dest);
FileChannel inch = in.getChannel();
FileChannel outch = out.getChannel();) {
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (inch.read(byteBuffer) != -1) {
byteBuffer.flip();
outch.write(byteBuffer);
byteBuffer.clear();
}
}
}
public static void main(String[] args) throws IOException {
File source = new File("E:\\hello.txt");
File dest = new File("E:\\hello2.txt");
copyFileByChannel(source, dest);
File dest2 = new File("E:\\hello3.txt");
Path path = source.toPath();
System.out.println("path===>" + path);
Files.copy(source.toPath(), dest2.toPath());
}
}