※non-Direct
try (
FileChannel in = new FileInputStream("1.jpg").getChannel();
FileChannel out = new FileOutputStream("2.jpg").getChannel();
) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (in.read(buffer) != -1) {
buffer.flip();
out.write(buffer);
buffer.clear();
}
System.out.println("copy complete!");
} catch (IOException e) {
e.printStackTrace();
}
※
※Direct 使用映射
OpenOption[] oo = { StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE };
try (
FileChannel in = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
FileChannel out = FileChannel.open(Paths.get("2.jpg"), oo);
) {
MappedByteBuffer inMap = in.map(MapMode.READ_ONLY, 0, in.size());
MappedByteBuffer outMap = out.map(MapMode.READ_WRITE, 0, in.size());
byte[] dst = new byte[inMap.limit()];
inMap.get(dst);
outMap.put(dst);
System.out.println("copy complete");
} catch (IOException e) {
e.printStackTrace();
}
※
※Direct
OpenOption[] oo = { StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE };
try (
FileChannel in = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
FileChannel out = FileChannel.open(Paths.get("2.jpg"), oo);
) {
in.transferTo(0, in.size(), out); // in 到 out
// out.transferFrom(in, 0, in.size()); // out 從 in 過來的
System.out.println("copy complete");
} catch (IOException e) {
e.printStackTrace();
}
※
沒有留言:
張貼留言