ace 发表于 2013-2-4 22:31:21

Java 新I/O

Java新IO所使用的结构
更接近于操作系统执行I/O的方式:通道和缓冲器。通过是包含煤层的矿藏,缓冲器则是派送到矿藏的卡车。唯一与通道交互的缓冲器是ByteBuffer。
旧I/O库中有三个类被修改了,用以产生FileChannel
public class GetChannel {public static void main(String[] args) throws IOException {    FileChannel fc = new FileOutputStream("data").getChannel();    fc.write(ByteBuffer.wrap("some text ".getBytes()));    fc.close();    fc = new RandomAccessFile("data", "rw").getChannel();    fc.position(fc.size());    fc.write(ByteBuffer.wrap("some more ".getBytes()));    fc.close();    fc = new FileInputStream("data").getChannel();    ByteBuffer buf = ByteBuffer.allocate(1024);    fc.read(buf);    // 让ByteBuffer做好让别人读的准备    buf.flip();    while (buf.hasRemaining())      System.out.print((char) buf.get());}}

转换数据
public class BufferToText {public static void main(String[] args) throws IOException {    //=======================第一次============================    FileChannel fc = new FileOutputStream("data").getChannel();    fc.write(ByteBuffer.wrap("some text ".getBytes()));    fc.close();    fc = new FileInputStream("data").getChannel();    ByteBuffer buf = ByteBuffer.allocate(1024);    fc.read(buf);    buf.flip();    System.out.println(buf.asCharBuffer()); //乱码    // 返回到数据开始的地方    buf.rewind();    //=======================第二次============================    String encoding = System.getProperty("file.encoding");    System.out.println("system file encoding is " + encoding);    fc = new FileOutputStream("data").getChannel();    // 进行decode    fc.write(ByteBuffer.wrap("some text ".getBytes("UTF-16BE")));    fc.close();    fc = new FileInputStream("data").getChannel();    buf.clear();    fc.read(buf);    buf.flip();    System.out.println(buf.asCharBuffer());    //=======================第三次============================    fc = new FileOutputStream("data").getChannel();    buf = ByteBuffer.allocate(24);    // 进行encode    buf.asCharBuffer().put("Some text");    fc.write(buf);    fc.close();    fc = new FileInputStream("data").getChannel();    buf.clear();    fc.read(buf);    buf.flip();    System.out.println(buf.asCharBuffer());}}

获得基本类型
public class GetData {public static void main(String[] args) {    ByteBuffer bb = ByteBuffer.allocate(1024);    int i = 0;    // 分配ByteBuffer后,缓冲器其内容全部为0,共检测了1024个值 bb.limit()=1024    while (i++ < bb.limit())      if (bb.get() != 0)      System.out.println("i = " + i);    bb.rewind();    bb.asCharBuffer().put("howdy!");    char c;    while ((c = bb.getChar()) != 0)      System.out.print(c + " ");System.out.println();    bb.rewind();    bb.asIntBuffer().put(987654321);    System.out.println(bb.getInt());    bb.rewind();    bb.asFloatBuffer().put(987654321);    System.out.println(bb.getFloat());    bb.rewind();}}


视图缓冲器
可以让我们通过某个特定的基本数据类型的视窗,查看其底层的ByteBuffer,ByteBuffer依然是存储数据的地方,所以我们对视图的修改会映射成为对ByteBuffer的修改。
public class IntBufferDemo {public static void main(String[] args) {    ByteBuffer bb = ByteBuffer.allocate(1024);    IntBuffer ib = bb.asIntBuffer();    ib.put(new int[] { 11, 22, 33, 45, 68 });    System.out.println("index 3 is " + ib.get(3));    ib.put(3, 3344);    ib.flip();    while (ib.hasRemaining())      System.out.print(ib.get() + " ");}}package nio;import java.nio.ByteBuffer;import java.nio.CharBuffer;import java.nio.DoubleBuffer;import java.nio.FloatBuffer;import java.nio.IntBuffer;import java.nio.LongBuffer;import java.nio.ShortBuffer;public class ViewBuffers {public static void main(String[] args) {    ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, 0, 0, 0, 0, 'a' });    bb.rewind();    System.out.print("Byte Buffer ");    while (bb.hasRemaining())      System.out.print(bb.position() + " -> " + bb.get() + ", ");    CharBuffer cb = ((ByteBuffer) bb.rewind()).asCharBuffer();    System.out.print("\r\nChar Buffer ");    while (cb.hasRemaining())      System.out.print(cb.position() + " -> " + cb.get() + ", ");    FloatBuffer fb = ((ByteBuffer) bb.rewind()).asFloatBuffer();    System.out.print("\r\nFloat Buffer ");    while (fb.hasRemaining())      System.out.print(fb.position() + " -> " + fb.get() + ", ");    IntBuffer ib = ((ByteBuffer) bb.rewind()).asIntBuffer();    System.out.print("\r\nInt Buffer ");    while (ib.hasRemaining())      System.out.print(ib.position() + " -> " + ib.get() + ", ");    LongBuffer lb = ((ByteBuffer) bb.rewind()).asLongBuffer();    System.out.print("\r\nLong Buffer ");    while (lb.hasRemaining())      System.out.print(lb.position() + " -> " + lb.get() + ", ");    ShortBuffer sb = ((ByteBuffer) bb.rewind()).asShortBuffer();    System.out.print("\r\nShort Buffer ");    while (sb.hasRemaining())      System.out.print(sb.position() + " -> " + sb.get() + ", ");    DoubleBuffer db = ((ByteBuffer) bb.rewind()).asDoubleBuffer();    System.out.print("\r\nDouble Buffer ");    while (db.hasRemaining())      System.out.print(db.position() + " -> " + db.get() + ", ");}}
ByteBuffer通过一个被“包装”过得8字节数组产生,然后通过各种不同的基本类型视图缓冲器显示出来
http://dl.iteye.com/upload/attachment/273937/2e2f4c7b-bd53-3613-83e5-a0bf9d1d2403.jpg


字节的存放次序
ByteBuffer一高位优先的形式存储数据
高位优先 big endian 将重要的字节存放在地址最低的存储器单元
低位有限 litter endian 将重要的字节存放在地址最高的存储器单元
public class Edians {public static void main(String[] args) {    ByteBuffer bb = ByteBuffer.wrap(new byte);    show(bb);    bb.order(ByteOrder.BIG_ENDIAN);    show(bb);    bb.order(ByteOrder.LITTLE_ENDIAN);    show(bb);}private static void show(ByteBuffer bb) {    bb.asCharBuffer().put("abcdef");    System.out.println(Arrays.toString(bb.array()));    bb.rewind();}}

用缓冲器操作数据
http://dl.iteye.com/upload/attachment/273940/06082bc4-29c9-3395-9f51-ae92ce25fbe0.jpg

Buffer有4个索引 mark:标记position:位置limit:界限capacity:容量
http://dl.iteye.com/upload/attachment/273943/9b4dbb91-2fbb-31a2-9a22-a696d66c3453.jpg
public class UsingBuffer {private static void scramble(CharBuffer buf) {    while (buf.hasRemaining()) {      buf.mark();      // get put 方法会向后移动position      char c1 = buf.get();      char c2 = buf.get();      // reset 方法 将position的值设为mark的值      buf.reset();      buf.put(c2).put(c1);    }}public static void main(String[] args) {    char[] data = "UsingBUffers".toCharArray();    ByteBuffer bb = ByteBuffer.allocate(data.length * 2);    CharBuffer cb = bb.asCharBuffer();    cb.put(data);    // 只能打印出position和limit直接的字符    // rewind 方法把position设置到缓冲器的开始位置    System.out.println(cb.rewind());    scramble(cb);    System.out.println(cb.rewind());    scramble(cb);    System.out.println(cb.rewind());}}
页: [1]
查看完整版本: Java 新I/O