-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAIO_Demo.java
116 lines (82 loc) · 3.06 KB
/
AIO_Demo.java
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package com.lxl.io;/**
* Description:
*
* @author Administrator
* @date 2020/9/5 14:49
*/
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/**
* ClassName AIO_Demo
*
* @Author Administrator
* @Date 2020/9/5 14:49
* Version 1.0
**/
public class AIO_Demo {
public static void main(String[] args) {
// writeAIO();
readAIO();
}
static void writeAIO() {
try {
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(Paths.get("out.txt"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
CompletionHandler<Integer, Object> handler = new CompletionHandler<Integer, Object>() {
@Override
public void completed(Integer result, Object attachment) {
System.out.println("Attachment:********************* " + attachment + " " + result
+ " bytes written");
System.out.println("CompletionHandler Thread ID:********************* "
+ Thread.currentThread().getId());
}
@Override
public void failed(Throwable e, Object attachment) {
System.err.println("Attachment: " + attachment + " failed with:");
e.printStackTrace();
}
};
System.out.println("Main Thread ID: " + Thread.currentThread().getId());
fileChannel.write(ByteBuffer.wrap("AAAAAAA".getBytes()), 0, "First Write",
handler);
Thread.sleep(2000);
// fileChannel.write(ByteBuffer.wrap("BBBBBBB".getBytes()), 0, "Second Write",
// handler);
System.out.println("Main Thread ID: " + "END!!!");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static void readAIO() {
Path file = Paths.get("out.txt");
AsynchronousFileChannel channel = null;
try {
channel = AsynchronousFileChannel.open(file);
} catch (IOException e) {
e.printStackTrace();
}
ByteBuffer buffer = ByteBuffer.allocate(100_000);
Future<Integer> result = channel.read(buffer, 0);
while (!result.isDone()) {
System.out.println("Read NOT OK!!!");
}
Integer bytesRead = null;
try {
bytesRead = result.get();
System.out.println(new String(buffer.array(), 0, bytesRead));
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("Bytes read [" + bytesRead + "]");
}
}