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

發佈了45 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章