1.输入输出#
由InputStream、OutputStream组成,其中FilterInputStream、FilterOutputStream分别为装饰器类的基类。
JDK1.1之后通过适配器模式将InputStream和OutputStream转换成了Reader和Writer。但功能不同前者面向字节流,后者面向字符流以方便提供unicode编码字符读取方式。适配器类为InputStreamReader和OutputStreamWriter。这两者可以将InputStream、OutputStream子类转换成Reader和Writer。
2.常用的使用方式#
3.标准输入输出#
System.in是一个InputStream可以被包装。System.out是一个PrintStream,而PrintStream是一个OutputStream,其已经被包装过。System.err同System.out。
PrintStream console = System.out;//可以简化输出
4.nio#
nio通过使用更接近操作系统执行I/O的方式:通道和缓冲器。来提高IO速度,旧的IO也被重写通过新IO的方式但是效率仍慢于NIO。
唯一直接与通道交互的缓冲器是ByteBuffer。
旧的IO中三个类被修改泳衣产生FileChannel(通道),分别是FileInputStream、FileOutputStream、RandomAccessFile。
FileChannel fc = new FileInputStream(filepath).getChannel();
ByteBuffer buff = ByteBuffer.allocate(Size);
fc.read(buff);
buff.flip();//传入缓冲器后通过flip()方法通知可以被读取。
FileChannel fc = new FileOuputputStream(filepath).getChannel();
fc.write(ByteBuffer.wrap("Something ".getBytes()));//通过wrap方法包装byte数组
buffer.clear();//写入完成后要清空流
转换数据###
ByteBuffer buff = ByteBuffer.allocate(Size);
buff.asShortBuffer().put((Short)123456);
buff.asCharBuffer().put("abcff");
//通过asShortBuffer()、asCharBuffer()可以转换成基本类型的视图
LongBuffer lb = buff.asLongBuffer();
lb.get();//一次从缓冲区中取出多个字节
缓冲区细节###
ByteBuffer buff = ByteBuffer.allocate(Size);
buff.position();//缓冲器当前指针位置
buff.limit();//缓冲器容量
buff.flip();//将limit设置为position,position设置为0,为读取缓冲区做准备
buff.mark();//将mark设置为position
buff.clear();//将position设为0,limit设置为容量
buff.hasRemaining();//是否还有元素介于position和limit之间
buff.remaining();//limit-position
buff.rewind();//将position设置为0
buff.reset();//将position设置为mark
内存映射文件###
如文件无法一次性读入内存,MappedByteBuffer提供了一种方法,像操作全部文件内容被读入内存一样的方式去读写文件。
MappedByteBuffer out = new FileOutputStream(filepath).getChannel().map(FileChannel.MapMode.REAT_WRITE, 0 , length);
out.put("abdc".getBytes());
网友评论