9.java.IO和java.NIO

2019-03-01  本文已影响0人  未知的证明

java.io中最核心的概念是流(Stream),面向流的编程。Java中要么就是输入流要不就是输出流,不可能两者都是。
Java.nio中有3个核心概念:Selector,Channel与Buffer。在Java点Nio中面向块(block)或者缓冲区编程的。Buffer本身是一块内存,底层实现上就是一个数组,数据的读写都是通过Buffer实现的。数据来自于Channel;数据从从Channel中读到Buffer中;不可能从Channel直接读到程序中,必须从Buffer中获得。在Nio中Buffer不仅可以读,还可以写,这种状态的实现是通过一个方法实现,Buffer中的flip(),可以转化读写方式,表示状态的反转,修改状态。
除了数组之外,buffer还提供了数据的结构化的访问方式,并且还可以追踪到系统的读写过程。

Java中的8中原生数据类型,都有各自的Buffer类型,如IntBuffer,LongBuffer,ByteBuffer以及CharBuffer等等。

Channel指的可以向其写入数据或者读取数据的对象,有点类似于java.io的Stream。所有的数据都是通过Buffer进行的,永远不会出现向Channel写入数据或者读取数据的情况。
与Stream不同的是,Channel是双向的,一个流只可能是InputSteam或者OutputSteam,Channel打开后则可以进行读取,写入或者是读写。
由于Channel是双向的,所以他能更好的发映出操作系统的真实情况;在Linux系统中,底层操作系统的通道就是双向的。

程序1

package com.liyuanfeng.nio;
import java.nio.IntBuffer;
import java.security.SecureRandom;
public class NioTest1 {
    public static void main(String[] args) {
        IntBuffer buffer = IntBuffer.allocate(10);
        for (int i = 0; i < buffer.capacity(); i++) {
            int randomNum = new SecureRandom().nextInt(20);
            buffer.put(randomNum);
        }
        buffer.flip();
        while (buffer.hasRemaining()) {
            System.out.println(buffer.get());
        }
    }
}

程序2

package com.liyuanfeng.nio;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NioTest2 {
    public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream = new FileInputStream("NioTest2.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);
        }
        fileInputStream.close();
    }
}

程序3

package com.liyuanfeng.nio;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NioTest3 {
    public static void main(String[] args) throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream("NioTest3.txt");
        FileChannel fileOutputStreamChannel = fileOutputStream.getChannel();
        ByteBuffer allocate = ByteBuffer.allocate(512);
        String hello = "Hello World !世界你好!";
        byte[] bytes = hello.getBytes();
        for (byte aByte : bytes) {
            allocate.put(aByte);
        }
        allocate.flip();
        fileOutputStreamChannel.write(allocate);
        fileOutputStream.close();
    }

}
上一篇 下一篇

猜你喜欢

热点阅读