Java NIO

1、IO與NIO的區別java

java.io 中最核心的一個概念是流(Stream),面向流的編程。一個流要麼是輸入流,要麼是輸出流,不可能同時便是輸入流又是輸出流。編程

 

java.nio中3個核心概念: Selector(選擇器), Channel(通道)與Buffer(緩衝區)。在java.nio中,咱們是面向塊(block)或是緩衝區(buffer)編程的。數組

  Bufferdom

  Buffer自己就是一塊內存,底層實現上,它其實是個數組。數據的讀、寫都是經過Buffer來實現的。操作系統

  除了數組以外,Buffer還提供了對於數據的結構化訪問方式,而且能夠追蹤到系統的讀寫過程。對象

  Java中的7種原生數據類型都有各自對應的Buffer類型,如IntBuffer,LongBuffer,ByteBuffer及CharBuffer等等,並無BooleanBufferblog

  Channelip

  Channel指的是能夠向其寫入數據或是從中讀取數據的對象,它相似於java.io中的Stream內存

  全部數據的讀寫都是經過Buffer來進行的,永遠不會出現直接向Channel寫入數據的狀況,或者直接從Channel讀取數據的狀況。ci

  與Stream不一樣的是,Channel是雙向的,一個流只多是InputStream或是OutputStream,Channel打開後則能夠進行讀取、寫入或是讀寫。

  因爲Channel是雙向的,所以它能更好地反映出底層操做系統的真實狀況;在Linux系統中,底層操做系統的通道就是雙向的。

 

2、Nio的例子1

public class NioTest
{
    public static void main(String[] args) {
        IntBuffer buffer = IntBuffer.allocate(10);

        for(int i = 0 ; i < buffer.capacity(); i++){
            int randomNumber = new SecureRandom().nextInt(20);
            buffer.put(randomNumber);
        }

        buffer.flip();

        while (buffer.hasRemaining()){
            System.out.println(buffer.get());
        }
    }
}

  flip是進行切換成讀。

打印結果:

 

3、傳統IO切換成NIO對象

public class NioTest2
{
    public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream = new FileInputStream("NioText2.txt");
        FileChannel fileChannel = fileInputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        fileChannel.read(byteBuffer);

        //操做反轉
        byteBuffer.flip();

        while (byteBuffer.remaining() > 0){
            byte b = byteBuffer.get();
            System.out.println("Character:" + (char)b );
        }

        fileChannel.close();
    }
}

  

新建NioText.txt文件

 

輸出結果

 

4、例子3

將信息寫入NioText3.txt文件中

public class NioTest3
{
    public static void main(String[] args) throws Exception {
        FileOutputStream fileOutputStream = new FileOutputStream("NioText3.txt");
        FileChannel fileChannel = fileOutputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        byte[] message = "hello world, welcome".getBytes();

        for(int i = 0; i < message.length ; i++){
            // 將信息寫入byteBuffer裏
            byteBuffer.put(message[i]);
        }

        byteBuffer.flip();

        //將byteBuffer信息寫入fileChannel
        fileChannel.write(byteBuffer);

        fileChannel.close();
    }
}
相關文章
相關標籤/搜索