nio(三) FileChannel
1.简介
JDK1.4在IO的基础上引入NIO,其目的在于提高速度。速度的提高来自于所使用的结构更接近于操作系统执行I/O的方式:通道和缓冲器。唯一直接与通道交互的缓冲器是ByteBuffer。
FileChannel是用于读取、写入、映射和操作文件的通道,目前不支持直接创建该对象,可通过FileInputStream,FileOutputStream,RandomAccessFile的getChannel方法获取FileChannel对象。
通过 FileInputStream 实例的 getChannel 方法所获得的通道将允许进行读取操作。通过 FileOutputStream 实例的 getChannel 方法所获得的通道将允许进行写入操作。最后,如果使用模式 "r" 创建 RandomAccessFile 实例,则通过该实例的 getChannel 方法所获得的通道将允许进行读取操作,如果使用模式 "rw" 创建实例,则获得的通道将允许进行读取和写入操作。
如果从文件输出流中获得了允许进行写入操作的文件通道,并且该输出流是通过调用 FileOutputStream(File,boolean) 构造方法且为第二个参数传入 true 来创建的,则该文件通道可能处于追加模式。在此模式中,每次调用相关的写入操作都会首先将位置移到文件的末尾,然后再写入请求的数据。在单个原子操作中是否移动位置和写入数据是与系统相关的,因此是未指定的。
文件通道在其文件中有一个当前 position,可对其进行查询和修改。该文件本身包含一个可读写的长度可变的字节序列,并且可以查询该文件的当前#size大小。写入的字节超出文件的当前大小时,则增加文件的大小;截取 该文件时,则减小文件的大小。文件可能还有某个相关联的元数据,如访问权限、内容类型和最后的修改时间;此类未定义访问元数据的方法。
除了字节通道中常见的读取、写入和关闭操作外,此类还定义了下列特定于文件的操作:
1)以不影响通道当前位置的方式,对文件中绝对位置的字节进行读取或写入。
2)将文件中的某个区域直接映射到内存中;对于较大的文件,这通常比调用普通的 read 或 write 方法更为高效。
3)强制对基础存储设备进行文件的更新,确保在系统崩溃时不丢失数据。
4)以一种可被很多操作系统优化为直接向文件系统缓存发送或从中读取的高速传输方法,将字节从文件传输到某个其他通道中,反之亦然。
5)可以锁定某个文件区域,以阻止其他程序对其进行访问。
多个并发线程可安全地使用文件通道。可随时调用关闭方法,正如 Channel 接口中所指定的。对于涉及通道位置或者可以更改其文件大小的操作,在任意给定时间只能进行一个这样的操作;如果尝试在第一个操作仍在进行时发起第二个操作,则会导致在第一个操作完成之前阻塞第二个操作。可以并发处理其他操作,特别是那些采用显式位置的操作;但是否并发处理则取决于基础实现,因此是未指定的。
确保此类的实例所提供的文件视图与同一程序中其他实例所提供的相同文件视图是一致的。但是,此类的实例所提供的视图不一定与其他并发运行的程序所看到的视图一致,这取决于基础操作系统所执行的缓冲策略和各种网络文件系统协议所引入的延迟。不管其他程序是以何种语言编写的,而且也不管是运行在相同机器还是不同机器上都是如此。此种不一致的确切性质取决于系统,因此是未指定的。
文件通道的状态与其 getChannel 返回该通道的对象密切相关。显式或者通过读取或写入字节来更改通道的位置将更改发起对象的文件位置,反之亦然。通过文件通道更改此文件的长度将更改通过发起对象看到的长度,反之亦然。通过写入字节更改此文件的内容将更改发起对象所看到的内容,反之亦然。
由于通道只能与ByteBuffer交互,所以必然存在字符和字节之间的转化问题,转化方法有两个:
1)使用Charset进行encode和decode实现字符和字节
2)使用Channels类将Channel转化为Reader或者Writer
最后要说的是旧的IO包已经使用NIO重新实现过,以便充分利用这种速度提高,因此,即使我们不显式地用NIO编写代码,也能从中受益。
2.实例
package com.siyuan.test.jdk.nio;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
public class FileChannelTest {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
int BUFFER_SIZE = 1024;
Charset gbk = Charset.forName("GBK");
/*
* 使用FileChannel写文件
*/
FileChannel fcW = new FileOutputStream("D:/test/fileChannelTest.txt").getChannel();
System.out.println(getFileChannelStatus(fcW));
fcW.write(gbk.encode("我是中国人")); //通过Charset.encode()方法创建的ByteBuffer已经进行了flip操作
System.out.println(getFileChannelStatus(fcW));
fcW.close();
/*
* 使用FileChannel读文件
*/
//FileChannel fcR = fcW; //java.nio.channels.NonReadableChannelException
FileChannel fcR = new FileInputStream("D:/test/fileChannelTest.txt").getChannel();
System.out.println(getFileChannelStatus(fcR));
ByteBuffer bBuffer = ByteBuffer.allocate(BUFFER_SIZE);
while (fcR.read(bBuffer) != -1) {
bBuffer.flip(); //
System.out.println(Charset.forName("GBK").decode(bBuffer));
bBuffer.clear(); //
}
System.out.println(getFileChannelStatus(fcR));
fcR.close();
/*
* 使用Channels创建Reader读取文件
*/
FileChannel fcR2 = new FileInputStream("D:/test/fileChannelTest.txt").getChannel();
BufferedReader bufR = new BufferedReader(Channels.newReader(fcR2, "GBK"));
String bufStr = null;
while ((bufStr = bufR.readLine()) != null) {
System.out.println(bufStr);
}
bufR.close();
/*
* 从一个文件读取内容到另一个文件
* 比较不同的方式下的速度
*/
// method 1
long timeStart0 = System.currentTimeMillis();
InputStream in = new BufferedInputStream(new FileInputStream("D:/test/2013-05-28.zip"));
OutputStream out = new BufferedOutputStream(new FileOutputStream("D:/test/2013-05-28-bak0.zip"));
byte[] buf = new byte[BUFFER_SIZE];
int length = 0;
while ((length = in.read(buf, 0, buf.length)) != -1) {
out.write(buf, 0, length);
}
in.close();
out.close();
System.out.println("Time cost of method 0 : " + (System.currentTimeMillis() - timeStart0));
// method 1
long timeStart1 = System.currentTimeMillis();
FileChannel fcIn = new FileInputStream("D:/test/2013-05-28.zip").getChannel();
FileChannel fcOut = new FileOutputStream("D:/test/2013-05-28-bak1.zip").getChannel();
while (fcIn.read(bBuffer) != -1) {
bBuffer.flip();
fcOut.write(bBuffer);
bBuffer.clear();
}
fcIn.close();
fcOut.close();
System.out.println("Time cost of method 1 : " + (System.currentTimeMillis() - timeStart1));
// method 2
long timeStart2 = System.currentTimeMillis();
FileChannel fcIn2 = new FileInputStream("D:/test/2013-05-28.zip").getChannel();
FileChannel fcOut2 = new FileOutputStream("D:/test/2013-05-28-bak2.zip").getChannel();
fcIn2.transferTo(0, fcIn2.size(), fcOut2);
fcIn2.close();
fcOut2.close();
System.out.println("Time cost of method 2 : " + (System.currentTimeMillis() - timeStart2));
// method 3
long timeStart3 = System.currentTimeMillis();
FileChannel fcIn3 = new FileInputStream("D:/test/2013-05-28.zip").getChannel();
FileChannel fcOut3 = new FileOutputStream("D:/test/2013-05-28-bak3.zip").getChannel();
fcOut3.write(fcIn3.map(FileChannel.MapMode.READ_ONLY, 0, fcIn3.size()));
fcIn3.close();
fcOut3.close();
System.out.println("Time cost of method 3 : " + (System.currentTimeMillis() - timeStart3));
}
public static String getFileChannelStatus(FileChannel fc) throws IOException {
StringBuilder fcStatus = new StringBuilder();
fcStatus.append("位置:").append(fc.position())
.append(",大小:").append(fc.size());
return fcStatus.toString();
}
}
运行结果
位置:0,大小:0
位置:10,大小:10
位置:0,大小:10
我是中国人
位置:10,大小:10
我是中国人
Time cost of method 0 : 245
Time cost of method 1 : 875
Time cost of method 2 : 581
Time cost of method 3 : 905
3.参考资料
JDK
THINKING IN JAVA