forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChannelCopy.java
More file actions
46 lines (32 loc) · 1.19 KB
/
ChannelCopy.java
File metadata and controls
46 lines (32 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.zetcode;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ChannelCopy {
public static void main(String[] args) throws IOException {
var srcFile = Paths.get("src/resources/beginning.txt");
var destFile = Paths.get("src/resources/beginning2.txt");
try (var src = Channels.newChannel(Files.newInputStream(srcFile))) {
try (var dest = Channels.newChannel(Files.newOutputStream(destFile))) {
copyBytes(src, dest);
}
}
}
private static void copyBytes(ReadableByteChannel src,
WritableByteChannel dest) throws IOException {
var buf = ByteBuffer.allocateDirect(1024);
while (src.read(buf) != -1) {
// flip the buffer from read to write
buf.flip();
// Make sure that the buffer was fully drained
while (buf.hasRemaining()) {
dest.write(buf);
}
buf.clear();
}
}
}