-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathChannelDemo.java
More file actions
65 lines (60 loc) · 1.77 KB
/
Copy pathChannelDemo.java
File metadata and controls
65 lines (60 loc) · 1.77 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.channels.Channels;
import java.nio.ByteBuffer;
import java.io.IOException;
public class ChannelDemo{
public static void main(String[] args){
ReadableByteChannel readChannel = Channels.newChannel(System.in);
WritableByteChannel writeChannel = Channels.newChannel(System.out);
try{
int command = (int)(Math.random() * 2);
switch(command){
case 0:
System.err.println("command = " + command + ", use copy(..) method.");
System.err.println();
copy(readChannel, writeChannel);
break;
case 1:
System.err.println("command = " + command + ", use copyAlt(..) method.");
System.err.println();
copyAlt(readChannel, writeChannel);
break;
}
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
try{
readChannel.close();
writeChannel.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}
static void copy(ReadableByteChannel readChannel, WritableByteChannel writeChannel) throws IOException{
ByteBuffer buffer = ByteBuffer.allocateDirect(2048);
while(readChannel.read(buffer) != -1){
buffer.flip();
writeChannel.write(buffer); // maybe not drain the buffer completely.
buffer.compact();
}
// read ended.
buffer.flip();
while(buffer.hasRemaining()){
writeChannel.write(buffer);
}
}
static void copyAlt(ReadableByteChannel readChannel, WritableByteChannel writeChannel) throws IOException{
ByteBuffer buffer = ByteBuffer.allocateDirect(2048);
while(readChannel.read(buffer) !=-1){
buffer.flip();
while(buffer.hasRemaining()){
writeChannel.write(buffer);
}
// Drained the buffer completely now.
buffer.clear();
// Ready for next read process.
}
}
}