`

Java 新I/O

    博客分类:
  • Java
阅读更多
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字节数组产生,然后通过各种不同的基本类型视图缓冲器显示出来



字节的存放次序
ByteBuffer一高位优先的形式存储数据
高位优先 big endian 将重要的字节存放在地址最低的存储器单元
低位有限 litter endian 将重要的字节存放在地址最高的存储器单元
public class Edians {
  public static void main(String[] args) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[12]);
    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();
  }
}


用缓冲器操作数据


Buffer有4个索引 mark:标记  position:位置  limit:界限  capacity:容量

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());
  }
}
  • 大小: 17.1 KB
  • 大小: 91 KB
  • 大小: 36.9 KB
  • nio.zip (3.5 KB)
  • 下载次数: 10
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics