IO byte stream 11 byte input stream read multiple bytes at a time

Posted by bb_sarkar on Wed, 09 Oct 2019 07:55:32 +0200


package com.itheima.demo02.InputStream;

import java.io.FileInputStream;
import java.io.IOException;

/*

A method of reading multiple bytes at a time by byte input stream:
    int read(byte[] b) reads a certain number of bytes from the input stream and stores them in the buffer array B.
Make two things clear:
    1. The function of the parameter byte [] of the method?
        It acts as a buffer to store multiple bytes read at a time.
        The length of an array is defined as an integer multiple of 1024(1kb) or 1024.
    2. what is the return value int of the method?
        Number of valid bytes read at a time

Construction Method of String Class
    String(byte[] bytes): Converting byte arrays to strings
    String(byte[] bytes, int offset, int length) converts part of the byte array to the string offset: the starting index length of the array: the number of bytes converted

*/
public class Demo02InputStream {

public static void main(String[] args) throws IOException {
    //Create the FileInputStream object and bind the data source to be read in the constructor
    FileInputStream fis = new FileInputStream("09_IOAndProperties\\b.txt");
    //Read files using the method read in the FileInputStream object
    //int read(byte[] b) reads a certain number of bytes from the input stream and stores them in the buffer array B.
    /*byte[] bytes = new byte[2];
    int len = fis.read(bytes);
    System.out.println(len);//2
    //System.out.println(Arrays.toString(bytes));//[65, 66]
    System.out.println(new String(bytes));//AB

    len = fis.read(bytes);
    System.out.println(len);//2
    System.out.println(new String(bytes));//CD

    len = fis.read(bytes);
    System.out.println(len);//1
    System.out.println(new String(bytes));//ED

    len = fis.read(bytes);
    System.out.println(len);//-1
    System.out.println(new String(bytes));//ED*/

    /*
        Loop optimization can be used to discover a repetitive process when reading above
        I don't know how many bytes there are in the file, so I use the while loop
        while The condition for the end of the loop, read to - 1
     */
    byte[] bytes = new byte[1024];//Store read bytes
    int len = 0; //Record the number of valid bytes read each time
    while((len = fis.read(bytes))!=-1){
        //String(byte[] bytes, int offset, int length) converts part of the byte array to the string offset: the starting index length of the array: the number of bytes converted
        System.out.println(new String(bytes,0,len));
    }

    //Release resources
    fis.close();
}

}

Topics: Java