public class App
{
/**
* io
* @throws Exception
*/
@Test
public void test_1() throws Exception{
FileInputStream is = new FileInputStream("D:/test.txt");
byte[] buffer = new byte[1024];
is.read(buffer);
System.out.println(new String(buffer));
is.close();
}
/**
* nio框架就是把用户缓冲区映射到系统缓冲区。也是面向块的io数据处理
* FileChannel
* ByteBuffer
*
* @throws Exception
*/
@Test
public void test_2()throws Exception{
FileInputStream is = new FileInputStream("D:/test.txt");
//为该文件输入流生成唯一的文件通道
FileChannel channel = is.getChannel();
//开辟一个长度为1024的字节缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);
System.out.println(new String(buffer.array()));
System.out.println(buffer.isDirect()+","+buffer.isReadOnly());
channel.close();
is.close();
}
}
在大文件或者初次读写小文件的情况下:NIO在性能上明显比IO性能好;
但是二次读写的情况下:NIO基本不变、IO性能有很大提升;这涉及到底层的具体实现,
传统IO是从磁盘到内核缓存区再到用户缓存区
NIO是内核缓冲区与用户缓冲区有一个映射。