packagecc.client;import java.io.*;importjava.net.InetSocketAddress;importjava.nio.ByteBuffer;importjava.nio.MappedByteBuffer;import java.nio.channels.*;public classClientOper {public static void main(String[] args) throwsIOException {
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()) {
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();*/}
}