BIO与NIO
BIO同步阻塞,在调用read方法则会阻塞当前线程等待(从主存中DMA copy至内核缓冲区,然后利用cpu将内核缓冲区的数据读取至进程缓冲区)
NIO过程一致,但是BIO需要一个线程监听一次读写状态,而NIO利用channal通道的概念,利用一个线程监听所有的通道(不断的自旋调用select(),查询是否可以读取),只要通道read完成,再通知读取线程读取
BIO读写文件
public void test(){
BufferedInputStream bf=new BufferedInputStream(new FileInputStream(new File("D://test.txt")));
BufferedOutputStream ot=new BufferedOutputStream(new FileOutputStream(new File("")));
int i=-1;
while((i=bf.read())!=-1){
ot.write(i);
}
bf.close();
ot.close();
}
NIO读写文件
FileInputStream fi=new FileInputStream(new File(""));
FileChannel channel = fi.getChannel();
FileOutputStream fo=new FileOutputStream(new File(""));
FileChannel channel1 = fo.getChannel();
ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
int length=-1;
int outLength=0;
while((length=channel.read(byteBuffer))!=-1){
byteBuffer.flip();
outLength=0;
while((outLength=channel1.write(byteBuffer))!=0){
channel1.write(byteBuffer);
}
byteBuffer.clear();
}