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阻塞

你可能感兴趣的:(java)