package com.timothy.socket.nio.file;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NioFile {
public static void copyFile(String sourcePath, String destPath) {
FileInputStream is = null;
FileChannel rChannel = null;
FileOutputStream os = null;
FileChannel wChannel = null;
try {
is = new FileInputStream(sourcePath);
rChannel = is.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
os = new FileOutputStream(destPath);
wChannel = os.getChannel();
int readBytes = 0;
while ((readBytes = rChannel.read(buffer)) > 0) {
// 写模式切换为读模式
buffer.flip(); // limit = position, position = 0
while (buffer.hasRemaining()) {
wChannel.write(buffer);
}
buffer.clear(); // position = 0, limit = capacity, mark=-1
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
rChannel.close();
wChannel.close();
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
String sourcePath = "D:\\test\\test1.txt";
String destPath = "D:\\test\\test2.txt";
NioFile.copyFile(sourcePath, destPath);
}
}