Java NIO 经典实例代码("Java NIO 实战经典代码示例")
原创
一、Java NIO 简介
Java NIO(Non-blocking I/O)是Java的一种非阻塞IO编程做法,它在Java 1.4中被引入,作为传统BIO(Blocking I/O)的替代方案。NIO提供了一系列新的API,用于处理文件和IO操作,关键包括Buffer、Channel、Selector等核心组件。以下是一些Java NIO的经典实例代码。
二、Buffer 的使用
Buffer 是Java NIO中的一个核心组件,它是一个可以存储数据的容器,用于在内存中存储数据。以下是一个使用Buffer的示例代码:
import java.nio.ByteBuffer;
public class BufferExample {
public static void main(String[] args) {
// 创建一个容量为10的ByteBuffer
ByteBuffer buffer = ByteBuffer.allocate(10);
// 向buffer中写入数据
for (int i = 0; i < buffer.capacity(); i++) {
buffer.put((byte) i);
}
// 切换到读模式
buffer.flip();
// 读取buffer中的数据
while (buffer.hasRemaining()) {
System.out.print(buffer.get() + " ");
}
}
}
三、Channel 的使用
Channel 是Java NIO中用于数据传输的组件,它类似于传统IO中的Stream。以下是一个使用Channel的示例代码:
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class ChannelExample {
public static void main(String[] args) {
try (FileChannel sourceChannel = FileChannel.open(Paths.get("source.txt"), StandardOpenOption.READ);
FileChannel targetChannel = FileChannel.open(Paths.get("target.txt"), StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
// 从sourceChannel读取数据并写入targetChannel
sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
} catch (Exception e) {
e.printStackTrace();
}
}
}
四、Selector 的使用
Selector 是Java NIO中用于处理多个Channel的组件,它可以监视多个注册的Channel上的事件(如连接请求、数据读写等)。以下是一个使用Selector的示例代码:
import java.nio.channels.*;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.Set;
public class SelectorExample {
public static void main(String[] args) {
try (Selector selector = Selector.open();
ServerSocketChannel serverSocket = ServerSocketChannel.open()) {
// 绑定端口
serverSocket.bind(new InetSocketAddress(8080));
// 设置为非阻塞模式
serverSocket.configureBlocking(false);
// 注册到Selector上,关注连接事件
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
// 非阻塞地检查是否有事件就绪
if (selector.select(1000) == 0) {
continue;
}
// 获取就绪的事件
Set
selectionKeys = selector.selectedKeys(); Iterator
iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isAcceptable()) {
// 处理连接事件
register(selector, serverSocket);
}
iterator.remove();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void register(Selector selector, ServerSocketChannel serverSocket) throws IOException {
SocketChannel client = serverSocket.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
System.out.println("New client registered: " + client);
}
}
五、 scattering 和 gathering 的使用
Scattering 和 Gathering 是Java NIO中的一种读写数据的做法,可以同时操作多个Buffer。以下是一个使用Scattering和Gathering的示例代码:
import java.nio.*;
import java.nio.channels.SocketChannel;
import java.net.InetSocketAddress;
public class ScatteringGatheringExample {
public static void main(String[] args) throws IOException {
// 创建一个散射缓冲区数组
ByteBuffer[] buffers = {ByteBuffer.allocate(10), ByteBuffer.allocate(20), ByteBuffer.allocate(30)};
// 向散射缓冲区写入数据
SocketChannel channel = SocketChannel.open();
channel.connect(new InetSocketAddress("localhost", 8080));
// 将数据写入散射缓冲区数组
channel.read(buffers);
// 调整缓冲区的位置
for (ByteBuffer buffer : buffers) {
buffer.flip();
}
// 创建一个聚集缓冲区数组
ByteBuffer[] gatherBuffers = {ByteBuffer.allocate(10), ByteBuffer.allocate(20), ByteBuffer.allocate(30)};
// 将数据从散射缓冲区数组写入聚集缓冲区数组
channel.write(gatherBuffers);
// 关闭通道
channel.close();
}
}
六、总结
本文介绍了Java NIO中的一些经典实例代码,包括Buffer、Channel、Selector、Scattering和Gathering等核心组件的使用。通过这些示例代码,我们可以更好地懂得Java NIO的非阻塞IO编程做法,从而在实际开发中应用这些技术,节约程序的并发性能。