JavaNIO中的内存映射io
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaNIO中的内存映射io相关的知识,希望对你有一定的参考价值。
客户端代码:
package cc.client; import java.io.*; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.*; public class ClientOper { public static void main(String[] args) throws IOException { File file=new File("test.txt"); RandomAccessFile raf=new RandomAccessFile(file, "rw"); FileChannel fileChannel=raf.getChannel(); //内存映射,将内核缓存区的内存进行映射,应用程序可以像操作用户缓存区一样向内核缓存区读写数据。 MappedByteBuffer mbb=fileChannel.map(FileChannel.MapMode.READ_WRITE, 0,1024 ); //写入数据 for(int i=0;i<1024;i++) mbb.put((byte)‘c‘); raf.close(); /* SocketChannel sChannel = SocketChannel.open(); sChannel.configureBlocking(false); //建立连接 sChannel.connect(new InetSocketAddress("127.0.0.1", 80)); while (!sChannel.finishConnect()) { System.out.println("等待非阻塞连接建立...."); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } //这时依旧需要CPU将内核缓冲区的内容拷贝到网络缓冲区 while(mbb.hasRemaining()) { sChannel.write(mbb); } fileChannel.close(); raf.close();*/ //测试消息成功写入了test文件 /*FileInputStream fs=new FileInputStream(file); byte[] bytes=new byte[1024]; StringBuilder stringb=new StringBuilder(); //开始读消息 int length; while((length=fs.read(bytes))!=-1) { stringb.append(new String(bytes,0,length)); } System.out.println(stringb); fs.close();*/ } }
服务端代码:
public class ServerOper { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub ServerSocketChannel serverSocket = ServerSocketChannel.open(); serverSocket.bind(new InetSocketAddress(80)); serverSocket.configureBlocking(false); SocketChannel socketChannel = null; while(socketChannel==null) { socketChannel=serverSocket.accept(); } ByteBuffer byteBuffer=ByteBuffer.allocate(1024); int numByetsRead; while((numByetsRead = socketChannel.read(byteBuffer)) != -1) { if (numByetsRead == 0) { // 如果没有数据,则稍微等待一下 try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } continue; } // 转到最开始 byteBuffer.flip(); while (byteBuffer.remaining() > 0) { System.out.print((char) byteBuffer.get()); } } socketChannel.close(); serverSocket.close(); } }
https://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ314_029.htm
以上是关于JavaNIO中的内存映射io的主要内容,如果未能解决你的问题,请参考以下文章
JavaNIO的深入研究4内存映射文件I/O,大文件读写操作,Java nio之MappedByteBuffer,高效文件/内存映射