Java NIO 随笔(二)


Java NIO数据通道传输:

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);


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);

SocketChannel的一些操作:

SocketChannel socketChannel =SocketChannel.open();
socketChannel.connect(new InetSocketAddress("http://www.baidu.com"),80);
socketChannel.close();

ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = socketChannel.read(buf);


String data ="hello";
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(data.getBytes());
buf.flip();

while(buf.hasRemaining())
    channel.write(buf);

socketChannel.configureBlocking(false);
非阻塞模式读需要没读到就可能返回,没写也可能返回


ServerSocketChannel: ServerSocketChannel 是可以监听TCP的socket

ServerSocketChannel serverSocketChannel= ServerSocketChannel.open()
serverSocketChannel.socket().bind(new InetSocketAddress(9999));
serverSocketChannel.configureBlocking(false);
while(true)
{
	SocketChannel socketChannel = serverSocketChannel.accept();
	if(socketChannel!=null)
	{
		//do task
	}
}
serverSocketChannel.close()


DatagramChannel收发UDP 包:

DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(9999));

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
channel.receive(buf);

String data ="abc";
ByteBuffer buf =ByteBuffer.allocate(48);
buf.clear();
buf.put(data.getBytes());
buf.flip();

int bytesSent = channel.send(buf,new InetSocketAddress("127.0.0.1",80));

Java NIO Pipe: 线程传递数据

Pipe pipe =Pipe.open();
Pipe.SinkChannel sinkChannel = pipe.sink();

String data ="abc";
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(data.getBytes());

buf.slip();
while(buf.hasRemaining())
{
	sinkChannel.write(buf);
}

Pipe.SourceChannel sourceChannel = pipe.source();
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = sourceChannel.read(buf);


IO 和NIO区别:


1. IO面向流,NIO 面向缓存区。NIO可前后移动
2. IO阻塞

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值