Java NIO使用技巧

本文深入讲解Java NIO的FileChannel和Selector的使用方法,包括如何通过transferFrom()和transferTo()实现通道间的数据直接传输,以及如何在一个Selector上注册多个Channel进行事件监听。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通道间直接传输数据

transferFrom()

FileChannel的transferFrom()方法可以将数据从源通道传输到FileChannel中。

RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
FileChannel      fromChannel = fromFile.getChannel();

RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
FileChannel      toChannel = toFile.getChannel();

long position = 0;
long count = fromChannel.size();

toChannel.transferFrom(position, count, fromChannel);

transferTo()

FileChannel的transferTo()方法可以将数据从FileChannel传输到其他的channel中。

RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
FileChannel      fromChannel = fromFile.getChannel();

RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
FileChannel      toChannel = toFile.getChannel();

long position = 0;
long count = fromChannel.size();

fromChannel.transferTo(position, count, toChannel);

一个Selector注册多个Channel

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class SocketChannelSelector {
    public static SocketChannel createSocketChannel(String hostName, int port)
            throws IOException {
        SocketChannel sChannel = SocketChannel.open();
        sChannel.configureBlocking(false);
        sChannel.connect(new InetSocketAddress(hostName, port));
        return sChannel;
    }

    // 2个连接注册的选择器关键字
    static SelectionKey key1;
    static SelectionKey key2;

    public static void main(String[] args) {
        // 1个选择器,注册2个Socket 通道
        Selector selector = null; // 调用完毕后记得关闭Selector selector.close();
        try {
            // 创建选择器
            selector = Selector.open();
            // 创建2个通道
            SocketChannel sChannel1 = createSocketChannel("163.net", 25);
            SocketChannel sChannel2 = createSocketChannel("mail.youkuaiyun.com", 25);
            // 注册选择器,侦听所有的事件
            key1 = sChannel1.register(selector, SelectionKey.OP_READ
                    | SelectionKey.OP_WRITE
                    | SelectionKey.OP_CONNECT);
            key2 = sChannel2.register(selector, sChannel2.validOps());
        } catch (IOException e) {
        }
        // 等待事件的循环
        while (true) {
            try {
                // 等待
                selector.select();
            } catch (IOException e) {
                break;
            }
            // 所有事件列表
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            // 处理每一个事件
            while (it.hasNext()) {
                // 得到关键字
                SelectionKey key = it.next();
                if (key.isAcceptable()) {
                    // a connection was accepted by a ServerSocketChannel.
                } else if (key.isConnectable()) {
                    // a connection was established with a remote server.
                } else if (key.isReadable()) {
                    // a channel is ready for reading
                } else if (key.isWritable()) {
                    // a channel is ready for writing
                }
                // 或者这样监听的感兴趣的事件
                int interestSet = selectionKey.interestOps();

                boolean isInterestedInAccept  = (interestSet & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT;
                boolean isInterestedInConnect = interestSet & SelectionKey.OP_CONNECT == SelectionKey.OP_CONNECT;
                boolean isInterestedInRead    = interestSet & SelectionKey.OP_READ == SelectionKey.OP_READ;
                boolean isInterestedInWrite   = interestSet & SelectionKey.OP_WRITE == SelectionKey.OP_WRITE;

                it.remove();
            }
        }
    }

}

Channel + Selector

从SelectionKey访问Channel和Selector很简单。如下:

Channel  channel  = selectionKey.channel();
Selector selector = selectionKey.selector();

 附加的对象

可以将一个对象或者更多信息附着到SelectionKey上,这样就能方便的识别某个给定的通道。例如,可以附加 与通道一起使用的Buffer,或是包含聚集数据的某个对象。使用方法如下:

selectionKey.attach(theObject);
Object attachedObj = selectionKey.attachment();

还可以在用register()方法向Selector注册Channel的时候附加对象。如:

SelectionKey key = channel.register(selector, SelectionKey.OP_READ, theObject);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值