FileChannel 从文件中读写数据。
FileChannelTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class FileChannelTest {
public static void main(String[] args) throws IOException { FileChannel inputFileChannel = new FileInputStream("file.text absolute path").getChannel(); ByteBuffer readBuffer = ByteBuffer.allocate(100); inputFileChannel.read(readBuffer); readBuffer.flip(); for (int i = 0; i < readBuffer.limit(); i++) { System.out.println((char) readBuffer.get()); }
FileChannel outputFileChannel = new FileOutputStream("file.text absolute path", true).getChannel(); ByteBuffer writeBuffer = ByteBuffer.wrap("TOM".getBytes()); outputFileChannel.write(writeBuffer);
inputFileChannel.close(); outputFileChannel.close(); } }
|
DatagramChannel 能通过UDP读写网络中的数据。
DatagramChannelServer.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class DatagramChannelServer { public static void main(String[] args) throws IOException { DatagramChannel channel = DatagramChannel.open(); channel.socket().bind(new InetSocketAddress(9999));
ByteBuffer buf = ByteBuffer.allocate(48); while (true) { channel.receive(buf); buf.flip(); for (int i = 0; i < buf.limit(); i++) { System.out.println((char) buf.get()); } buf.clear(); } } }
|
DatagramChannelClient.java
1 2 3 4 5 6 7 8
| public class DatagramChannelClient { public static void main(String[] args) throws IOException { DatagramChannel channel = DatagramChannel.open(); ByteBuffer buf = ByteBuffer.allocate(48); buf = buf.wrap("AA".getBytes()); channel.send(buf, new InetSocketAddress("localhost", 9999)); } }
|
ServerSocketChannel 可以监听新进来的TCP连接,像Web服务器那样。对每一个新进来的连接都会创建一个SocketChannel。
SocketChannel 能通过TCP读写网络中的数据。
NioChannelServer.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class NioChannelServer { public static void main(String[] args) throws IOException { ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(9999)); ByteBuffer buf = ByteBuffer.allocate(48); while (true) { SocketChannel channel = serverSocketChannel.accept(); while (true) { channel.read(buf); buf.flip(); for (int i = 0; i < buf.limit(); i++) { System.out.println((char) buf.get()); } buf.clear(); } } } }
|
NioChannelClient.java
1 2 3 4 5 6 7 8 9 10
| public class NioChannelClient { public static void main(String[] args) throws IOException { SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress("localhost", 9999)); while (true) { Scanner input = new Scanner(System.in); socketChannel.write(ByteBuffer.wrap(input.nextLine().getBytes())); } } }
|
Nio源码地址github.com