NIO的学习
/**
* nio不同于传统的 stream i/o, nio 是一种 block i/o
*
* nio 将最耗时的I/O操作(提取/填充缓冲区)的动作转回给操作系统
*
* 传统的 i/o 一次一个字节的处理数据(一个输入流产生一个字节的数据,一个输出流消费一个字节的数据,流式数据创建过滤器很容易,确定是比较慢)
*
* nio采用的块的方式来处理数据,每一个操作都在一步中产生或者消费一个数据块
*
* nio库中,所有的数据都是用缓冲区处理的。读取数据的时候,它是直接到缓冲区中的。写入数据的时候,它是写入到缓冲区中的。任何时候访问NIO中的数据,都是将其放入到缓冲区中的
*
* 缓冲区实质上是一个数组。
*
* 通常它是一个字节数据,但是也可以使用其他种类的数组。但它又不仅仅是一个数组
*
* 缓冲数组提供了对数据的结构化访问,而且还可以跟踪系统的 读/写 进程。
*
* 弄清楚 通道和缓存
*
* 最常用的缓冲区类型是 ByteBuffer。 一个ByteBuffer可以在其底层字节数组上进行 get/set操作
*
* Channel 是一个对象,可以通过它读取和写入数据。如前面提到的,所有数据都通过Buffer对象来处理。你不可能将字节流直接写入到通道中,
*
* 相反,你是将数据写入包含一个或多个字节的缓冲区
*
* 同样,你不会直接从通道中读取字节,而是将数据从通道中读入缓冲区中,再从缓冲区获取这个字节
*
* 通道的类型:通道与流的不同之处在于通道是双向的。而流只是在一个方向上移动(一个流必须是InputStream或者OutputStream的子类),通道可以用于读、写或者同时用于读写。(双向通信)
*
* @author michael
*
*/
下面的一个简单的文件复制的例子:
1).使用NIO的方式
public void copyFile() throws Exception{
//读入
FileInputStream inputStream = new FileInputStream("Test.txt");//源文件
FileOutputStream outputStream = new FileOutputStream("TestCopy.txt");
ByteBuffer buffer = ByteBuffer.allocate(1024);//设置缓冲区
if(inputStream != null) {
FileChannel inChannel = inputStream.getChannel();
FileChannel outChannel = outputStream.getChannel();
while(inChannel.read(buffer) != -1){
buffer.flip();//写入之前要进行 flip 操作(反转缓冲区,为一系列的写入或者获取操作做好准备)
outChannel.write(buffer);
buffer.clear();//读入之前要进行 clear 操作(重置缓冲区)
}
}
}
2).使用传统的Stream方式
public void copyFile() {
try {
File fileIn = new File(fromFile);
File fileOut = new File(toFile);
FileInputStream fin = new FileInputStream(fileIn);
FileOutputStream fout = new FileOutputStream(fileOut);
byte[] buffer = new byte[8192];//这里定义一个字节缓冲数组
while (fin.read(buffer) != -1) {//读入缓冲数组
fout.write(buffer);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
//关闭各种流
}
}
3).使用Buffered...Stream的方式
public void copyFile() {
try {
File fileIn = new File(fromFile);
File fileOut = new File(toFile);
FileInputStream fin = new FileInputStream(fileIn);
BufferedInputStream bin = new BufferedInputStream(fin);//使用BufferedInputStream
FileOutputStream fout = new FileOutputStream(fileOut);
byte[] buffer = new byte[8192];
while (bin.read(buffer) != -1) {
fout.write(buffer);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
//关闭各种流
}
}

浙公网安备 33010602011771号