NIO流是一个比IO流(字节字符)效率高很多,因为是以块为传输单位的,比较特殊;
java.nio.Buffer缓冲区
capacity() :表明缓冲区的容量大小, 一旦确定了大小, 将不能再改变;
limit() :告诉您到目前为止已经往缓冲区填了多少字节,或者让您用 :limit(int newLimit) 来改变这个限制
position() :告诉您当前的位置,以执行下一个读/写操作
mark() :为了稍后用 reset() 进行重新设置而记住某个位置
flip() :交换限制指针和位置指针,然后将位置置为 0,并废弃已经做的mark标记
Buffer + Channal共同使用读写文件(高效率):
try {
//读文件的流
FileInputStream fis = new FileInputStream( "e:\\Test.txt" );
FileChannel fc = fis.getChannel();
ByteBuffer bb = ByteBuffer.allocate( 5 );
//写文件的流
FileOutputStream fos = new FileOutputStream( "e:\\Test2.txt" );
FileChannel fc2 = fos.getChannel();
int iRes = 0;
while( true ) {
bb.clear();
iRes = fc.read( bb );
if ( -1 == iRes ) {
break;
}
// 对limit后面的缓冲区不进行操作;把position变成limit;
// 若是不filp的话get的话会出现乱码或者会出错
bb.flip();
Charset c = Charset.forName( "GBK" );
CharsetDecoder cd = c.newDecoder();
CharBuffer cb = cd.decode( bb );
System.out.println( cb.toString() );
fc2.write( bb );
}
// 防止缓存
fc.force(true);
fis.close();
fc.close();
fos.close();
fc2.close();
System.out.println( "ok!" );
} catch ( Exception e ) {
System.out.println( e.getMessage() );
}
-EOF-