读文件
FileChannel fileChannel = FileChannel.open(Path.of("file.txt"), StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024 * 32);
int size = fileChannel.read(buffer);
fileChannel.close();
写文件
FileChannel fileChannel = FileChannel.open(Path.of("file.txt"), StandardOpenOption.WRITE);
fileChannel.write(ByteBuffer.wrap("Hello world!".getBytes()));
fileChannel.close();
连接Socket
InetSocketAddress socketAddress = new InetSocketAddress("www.baidu.com", 80);
SocketChannel socketChannel = SocketChannel.open();
socketChannel.write(ByteBuffer.wrap("GET / HTTP/1.0\r\n\r\n".getBytes(StandardCharsets.ISO_8859_1)));
ByteBuffer buffer = ByteBuffer.allocate(1024 * 32);
int len;
while ((len = socketChannel.read(buffer)) > 0) {
buffer.flip();
System.out.println(new String(buffer.array(), 0, len));
}
socketChannel.close();