核心代码
package nio;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class NIOOperateFile {
public static void main(String[] args) {
try {
randomAccessFileCopy();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void copyFileUseNIO() throws Exception {
FileChannel fiChannel = new FileInputStream("C:\\Users\\lihw\\Desktop\\12.jpg").getChannel();
FileChannel foChannel = new FileOutputStream("C:\\Users\\lihw\\Desktop\\test\\12.jpg").getChannel();
ByteBuffer bf = ByteBuffer.allocate(1024);
while (fiChannel.read(bf) != -1) {
bf.flip();
foChannel.write(bf);
bf.clear();
}
fiChannel.close();
foChannel.close();
System.out.println("copy success");
}
public static void randomAccessFileCopy() throws Exception {
RandomAccessFile in = new RandomAccessFile("C:\\Users\\lihw\\Desktop\\12.jpg", "r");
RandomAccessFile out = new RandomAccessFile("C:\\Users\\lihw\\Desktop\\test\\12.jpg", "rw");
FileChannel fcInput = in.getChannel();
FileChannel fcOutput = out.getChannel();
long size = fcInput.size();
MappedByteBuffer mbbIn = fcInput.map(FileChannel.MapMode.READ_ONLY, 0, size);
MappedByteBuffer mbbOut = fcOutput.map(FileChannel.MapMode.READ_WRITE, 0, size);
for (var i = 0; i < size; i++) {
mbbOut.put(mbbIn.get());
}
fcInput.close();
fcOutput.close();
in.close();
out.close();
System.out.println("映射成功");
}
}