异步I/O操作
异步I/O-将来式
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
29public static void main(String[] args) {
try {
Path file = Paths.get("/usr/karianna/foobar.txt");
//异步打开文件
AsynchronousFileChannel channel = AsynchronousFileChannel
.open(file);
ByteBuffer buffer = ByteBuffer.allocate(100_000);
Future<Integer> result = channel.read(buffer, 0);
//判断result是否结束
while (!result.isDone()) {
ProfitCalculator.calculateTax();
}
Integer bytesRead = result.get();
System.out.println("Bytes read [" + bytesRead + "]");
} catch (IOException | ExecutionException | InterruptedException e) {
System.out.println(e.getMessage());
}
}
private static class ProfitCalculator {
public ProfitCalculator() {
}
public static void calculateTax() {
}
}异步I/O-回调式
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
27public static void main(String[] args) {
try {
Path file = Paths.get("/usr/karianna/foobar.txt");
AsynchronousFileChannel channel = AsynchronousFileChannel
.open(file);
ByteBuffer buffer = ByteBuffer.allocate(100_000);
channel.read(buffer, 0, buffer,
new CompletionHandler<Integer, ByteBuffer>() {
public void completed(Integer result,
ByteBuffer attachment) {
System.out.println("Bytes read [" + result + "]");
}
public void failed(Throwable exception,
ByteBuffer attachment) {
System.out.println(exception.getMessage());
}
});
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
NetworkChannel
获取当前主机networkinterface列表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
32public static void main(String[] args) {
try {
Enumeration<NetworkInterface> interfaceList = NetworkInterface
.getNetworkInterfaces();
if (null == interfaceList) {
System.out.println("--No intercaces found--");
} else {
while (interfaceList.hasMoreElements()) {
NetworkInterface iface = interfaceList.nextElement();
System.out.println("Interface " + iface.getName() + ":");
Enumeration<InetAddress> addrList = iface
.getInetAddresses();
if (!addrList.hasMoreElements()) {
System.out
.println("\t(No addresses for this interface)");
}
while (addrList.hasMoreElements()) {
InetAddress address = addrList.nextElement();
System.out
.print("\tAddress "
+ ((address instanceof Inet4Address ? "(v4)"
: (address instanceof Inet6Address ? "(v6)"
: "(?)"))));
System.out.println(": " + address.getHostAddress());
}
}
}
} catch (SocketException se) {
System.out.println("Error getting network interfaces:"
+ se.getMessage());
}
}