Java’s IO/NIO/OKIO

BIO = blockingio

AIO = Asynchronous IO

Read from memory to write–output

From external to memory — input

OutputStream //The file will be automatically created if it does not exist.

 try {
            OutputStream outputStream = new FileOutputStream("text.txt");
            outputStream.write('a');
            outputStream.write('b');
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

Reading and writing actually open up space in the memory, and then read and write, which need to be released in time.

Reader—-BufferReader

 try (InputStream inputStream = new FileInputStream("text.txt")){ //1
            Reader reader = new InputStreamReader(inputStream); //2
            BufferedReader bufferedReader = new BufferedReader(reader); // 3, increase buffer
            System.out.println(bufferedReader.readLine());
            inputStream.close();
        } catch (IOException e) {
            //close

            throw new RuntimeException(e);
        } finally {
            //close
        }

Nested three levels

BufferRead read ahead to increase performance

Default 8192 bytes

private static int defaultCharBufferSize = 8192;
private static int defaultExpectedLineLength = 80;
bufferedOutputStream.write needs to actively flush or wait until the buffer 8192 bytes is full before writing because there is buffering

It will also automatically flush when closing close.

 try (OutputStream outputStream = new FileOutputStream("text.txt");
             BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) {}//This method will also automatically flush

Android copy file FileUtils.copy

copy file

try (InputStream inputStream = new FileInputStream("text.txt");
             OutputStream outputStream = new FileOutputStream("text1.txt")) {

            byte[] data = new byte[1024]; //bytes read each time
            int read;//The number of reads
            while ((read = inputStream.read(data)) != -1) {
//Reading is a cyclic process. Write as much as you read. If you finish reading, it will be -1
//Write bytes from the starting position to the number read
                outputStream.write(data, 0, read);
            }

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

You can reduce its interaction and increase performance through buffer

 try (InputStream inputStream = new BufferedInputStream(new FileInputStream("text.txt"));
             OutputStream outputStream = new BufferedOutputStream(new FileOutputStream("text1.txt"))) {

            byte[] data = new byte[1024];
            int read;
            while ((read = inputStream.read(data)) != -1) {
                outputStream.write(data, 0, read);
            }

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

Otherwise, the frequency of each read and write interaction will be higher.

Socket:

 try (Socket socket = new Socket("sougou.com", 80);
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
             BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
            // getOutputStream writes
            //getInputStream read
            writer.write("GET / HTTP/1.1\\
" + "HOST: www.example.com\\
\\
"); //Request message
            writer.flush(); //Submit
            String message;
            while ((message = reader.readLine()) != null) {
                //Read the corresponding content
                System.out.println(message);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

NIO

Traditional IO Stream/Pipeline

NIO Channel/ Bidirectional

NIO Buffer

Buffer can be operated, forced to use

Non-blocking //Supports non-blocking, default blocking, only network interaction supports non-blocking, file interaction is not supported

 try {

            //capacity limit upper limit, mobile position generally unchanged
            //position position, pointer position
//r read permission,w write permission
            RandomAccessFile randomAccessFile = new RandomAccessFile("text.txt","rw");
            FileChannel fileChannel = randomAccessFile.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024); //Reading is currently not supported
            fileChannel.read(byteBuffer);

//These two lines are equivalent to the following line
            byteBuffer.limit(byteBuffer.position());
            byteBuffer.position(0);
            
//Equal to this way of writing
            byteBuffer.flip();

            System.out.println();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

Always clear after reading

byteBuffer.clear();

Blocking NIO

 try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.bind(new InetSocketAddress(80));
            SocketChannel socketChannel = serverSocketChannel.accept();//Blocking style
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            socketChannel.read(byteBuffer);
            byteBuffer.flip();
            System.out.println(byteBuffer);
            byteBuffer.clear();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

non-blocking

serverSocketChannel.configureBlocking(false); //Default true blocking
 try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.bind(new InetSocketAddress(80));

            serverSocketChannel.configureBlocking(false);//Non-blocking
            Selector selector = Selector.open();//selector
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);//Register
            while (true){
                selector.select();//select
                for (SelectionKey key : selector.selectedKeys()){
                    if (key.isAcceptable()){
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        while (socketChannel.read(byteBuffer) != -1){
                            byteBuffer.flip();
                            System.out.println(byteBuffer);
                            byteBuffer.clear();
                        }
                    }else break;
                }
            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }

OKIO

Packaging based on NIO

It is also based on pipelines, one-way Source and Sink

Supports Buffer / can operate on Buffer / does not force the use of Buff

read(buffer) buffer is a writing operation

Retrieving from the buffer is a read operation, and reading from the buffer is a write operation.

File().copyTO

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeNIONIO Overview 139294 people are learning the system