NIO的操作模式:
== PIO:==所有的操作由CPU进行处理,CPU占用比较高,不建议使用。
==DMA:==CPU把IO操作控制权交给DMA控制器,只能以固定的方式进行读写,CPU可以空闲做其他事情。
通道方式: 能执行有限通道指令的IO控制器,代替CPU管理控制外设,通道有自己的指令系统,是一个协处理
器,具有更强大的数据输入输出能力
Java NIO 由以下几个核心部分组成:
== Buffer :缓冲区==
== Channel:通道 Selector:==
==选择器(轮询器) ==
NIO和普通IO的区别:
Buffer的使用
Java NIO中的Buffer用于和NIO通道进行交互。如你所知,数据是从通道读入缓冲区,从缓冲区写入到通道中的。缓冲区本质上是一块可以写入数据,然后可以从中读取数据的内存。这块内存被包装成NIO Buffer对象,并提供了 一组方法,用来方便的访问该块内存。
基本用法
1 创建缓冲区,写入数据到Buffer
2. 调flip()方法
3 从Buffer中读取数据
4 调用clear()方法或者compact()方法 当向buffer写入数据时,buffer会记录下写了多少数据。一旦要读取数据,需要通过flip()方法将Buffer从写模 式切换到读模式。在读模式下,可以读取之前写入到buffer的所有数据。 一旦读完了所有的数据,就需要清空缓冲区,让它可以再次被写入。有两种方式能清空缓冲区:调用clear()或 compact()方法。clear()方法会清空整个缓冲区。compact()方法只会清除已经读过的数据。任何未读的数据 都被移到缓冲区的起始处,新写入的数据将放到缓冲区未读数据的后面。
代码实现:
public class Main {
public static void main(String[] args) {
ByteBuffer buffer= ByteBuffer.allocate( 1024 );
buffer.put( "hello".getBytes() );
buffer.flip();
/*byte b = buffer.get();
System.out.println((char)(b));*/
byte[]data=new byte[buffer.limit()];
buffer.get(data);
System.out.println(new String(data) );
}
}
写入文本文件:
public class Demo5 {
public static void main(String[] args)throws Exception{
FileChannel fileChannel=FileChannel.open( Paths.get( "hello.txt" ), StandardOpenOption.WRITE,StandardOpenOption.CREATE );
ByteBuffer buffer = ByteBuffer.allocate( 1024 );
for (int i = 0; i <10; i++) {
buffer.put( "xuexi".getBytes() );
buffer.flip();
fileChannel.write( buffer );
buffer.clear();
}
fileChannel.close();
}
}
读取文本文件:
public static void main(String[] args)throws Exception{
/* RandomAccessFile rad=new RandomAccessFile( "info.txt","r" );
FileChannel channel = rad.getChannel();*/
FileChannel fileChannel=FileChannel.open( Paths.get( "info.txt" ) );
ByteBuffer allocate = ByteBuffer.allocate( 1024 );
while (fileChannel.read(allocate)>0){
allocate.flip();//使用filp之后写模式变成读模式
String data=new String(allocate.array(),0,allocate.limit());
System.out.println(data);
allocate.clear();
}
fileChannel.close();
}
}
复制图片:
public class Denmo6 {
public static void main(String[] args)throws Exception{
FileChannel readChannel=FileChannel.open( Paths.get( "d:\\qq截图\\1.jpg"), StandardOpenOption.READ );
FileChannel writeChannel=FileChannel.open( Paths.get( "aaa.jpg"), StandardOpenOption.WRITE,StandardOpenOption.CREATE );
ByteBuffer buf = ByteBuffer.allocate( 1024 );
while (readChannel.read( buf )>0){
buf.flip();
writeChannel.write( buf );
buf.clear();
}
readChannel.close();
writeChannel.close();
}
}