Java Nio之基礎篇

Non-blocking IO

三大組件

  • Channel
    ** FileChannel
    ** DatagramChannel
    ** SocketChannel
    ** ServerSocketChannel
  • Buffer
    ** ByteBuffer
    ** CharBuffer
    ** DoubleBuffer
    ** FloatBuffer
    ** LongBuffer
    ** IntBuffer
    ** ShortBuffer
    ** MappedByteBuffer
  • Selector
    ** 單線程處理多個Channel
    ** 向Selector中註冊Channel, 調用select()方法阻塞

基本用法

  • channel是雙向的, 與buffer交互
public static void testFileBuffer() throws IOException {
    RandomAccessFile raFile = new RandomAccessFile("README.md", "rw");
    FileChannel inChannel = raFile.getChannel();

    ByteBuffer buffer = ByteBuffer.allocate(48);//capacity置爲48,即分配48字節的空間
    int byteRead = inChannel.read(buffer);//從channel中讀,向buffer中寫入數據
    while (byteRead != -1) {
        System.out.println(byteRead);
        buffer.flip();//轉換buffer到讀狀態,position重置爲0,limit置爲寫模式下的position
        System.out.println(new String(buffer.array(), "UTF-8"));
        while (buffer.hasRemaining()) {
            System.out.println((char)buffer.get());//從buffer中拿到數據,以字節爲單位
        }

        buffer.clear();//clear()清空buffer或compact()清除已讀數據
        byteRead = inChannel.read(buffer);
        System.out.println(byteRead);
    }
    raFile.close();
}

Buffer的三個屬性

  • capacity
  • position
  • limit
  • flip()方法
  • rewind()方法
  • clear()與compact()方法
  • equals()與compareTo()方法

通道之間的數據傳輸

  • 條件是其中一個通道是FileChannel
  • FileChannel有兩個方法
    ** transferFrom()
    ** transferTo()
  • 示例
public static void testChannelTransfer() throws IOException {
    RandomAccessFile fromFile = new RandomAccessFile("README.md", "rw");
    FileChannel fromChannel = fromFile.getChannel();
    RandomAccessFile toFile = new RandomAccessFile("nio-file.txt", "rw");
    FileChannel toChannel = toFile.getChannel();

    int position = 0;
    long count = fromChannel.size();
    toChannel.transferFrom(fromChannel, position, count);

    ByteBuffer buffer = ByteBuffer.allocate(1024);
    toChannel.read(buffer);
    System.out.println(new String(buffer.array()));
}

參考連接

相關文章
相關標籤/搜索