1, BIO(Blocking IO)传统的IO流,同步阻塞式IO,效率低,需要大量线程,编程简单
2,NIO(NonBlocking IO)java1.4出现的新的IO方式,同步非阻塞式IO,效率高,不需要大量线程,编程复杂
3,AIO(Asynchronize IO) 异步非阻塞式IO,效率高,编程复杂
举个例子:
烧开水
BIO 等在旁边什么都不干,直到水烧开
NIO 可以做其它事情,需要隔一段时间过来看看
AIO 可以做其它事情,水烧开会自动通知他
NIO的API:
传统的IO面向的是流
NIO面向的是块
Buffer 缓冲区
Channel 通道
Selector 多路复用器
代码实现:
public class NioTest {
public static void copy(String source,String target){
//创建文件流
try (FileInputStream in = new FileInputStream(source);
FileOutputStream out = new FileOutputStream(target)
){
//创建文件通道
FileChannel inChannel = in.getChannel();
FileChannel outChannel = out.getChannel();
//创建文件缓冲区
ByteBuffer buffer = ByteBuffer.allocate(100);
int len = 0;
//数据读出来写入到buffer中
while ((len = inChannel.read(buffer)) != -1){
//将buffer的状态,从写状态切换到读状态
buffer.flip();
//将buffer的数据写到输出通道
outChannel.write(buffer);
//清除原来的数据
buffer.rewind();
}
inChannel.close();
outChannel.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
copy("C:\\Users\\admin\\Desktop\\杂物.txt","C:\\Users\\admin\\Desktop\\杂物1111.txt");
}
}
运行效果: