04 use of byte stream

1, Byte input stream: read one byte at a time

IO architecture diagram

 

File byte input stream: FileInputStream

Function: take the memory as the benchmark to read the data in the disk file into the memory in the form of bytes.

constructor explain
public FileInputStream(File file) Create a byte input stream pipeline to connect with the source file object
public FileInputStream(String pathname) Create a byte input stream pipeline to connect with the source file path

​​ 

Method name explain
public int read() Read one byte at a time and return - 1 if the byte is no longer readable
public int read(byte[] buffer) Each time a byte array is read, it returns - 1 if the byte is no longer readable

[code example]

public class FileInputStreamDemo01 {
    public static void main(String[] args) throws Exception {
       // 1. Create a file byte input stream pipeline to connect with the source file.
        // InputStream is = new FileInputStream(new File("file-io-app\\src\\data.txt"));
        // Simplified writing
        InputStream is = new FileInputStream("file-io-app\\src\\data.txt");

        // 2. Read one byte and return (one drop of water each time)
//        int b1 = is.read();
//        System.out.println((char)b1);   
//
//        int b2 = is.read();
//        System.out.println((char)b2);
//
//        int b3 = is.read();
//        System.out.println((char)b3);
//
//        int b4 = is.read(); //  After reading, return to - 1
//        System.out.println(b4);

        // 3. Use cycle improvement
        // Define a variable to record bytes a, B and 3 love read each time. Because "love" has three bytes, there will be garbled code
        //                              o o  o   [ooo]
        int b;
        while (( b = is.read() ) != -1){
            System.out.print((char) b);
        }
    }
}

 

2, Byte input stream: read one byte array at a time

File byte input stream: FileInputStream

Function: take the memory as the benchmark to read the data in the disk file into the memory in the form of bytes.

Method name explain
public int read() Read one byte at a time and return - 1 if the byte is no longer readable
public int read(byte[] buffer) Each time a byte array is read, it returns - 1 if the byte is no longer readable

 

What is the problem with reading one byte array at a time?

Read performance has been improved

Reading Chinese character output cannot avoid garbled code

 

[code example]

/**
   Target: use the file byte input stream to read the data of one byte array at a time.
 */
public class FileInputStreamDemo02 {
    public static void main(String[] args) throws Exception {
        // 1. Create a file byte input stream pipeline to connect with the source file
        InputStream is = new FileInputStream("file-io-app/src/data02.txt");

        // 2. Defines a byte array for reading byte arrays
//        byte[] buffer = new byte[3]; // 3B
//        int len = is.read(buffer);
//        System.out.println("several bytes read:" + len);
//        String rs = new String(buffer);
//        System.out.println(rs);
//
//        int len1 = is.read(buffer);
//        System.out.println("several bytes read:" + len1);
//        String rs1 = new String(buffer);
//        System.out.println(rs1);
//        // buffer = [a b c]
//
//        // buffer = [a b c]  ==>  [c d c]
//        int len2 = is.read(buffer);
//        System.out.println("several bytes read:" + len2);
//        //How much to read and how much to pour out
//        String rs2 = new String(buffer,0 ,len2);
//        System.out.println(rs2);
//
//        int len3 = is.read(buffer);
//        System.out.println(len3); //  After reading, return to - 1

        // 3. Improved use of loops to read one byte array at a time
        byte[] buffer = new byte[3];
        int len; // Record the number of bytes read each time.
        while ((len = is.read(buffer)) != -1) {
            // How much to read and how much to pour out
            System.out.print(new String(buffer, 0 , len));
        }
    }
}

 

3, Byte input stream: read all bytes at one time

Question:

1. How to use byte input stream to read Chinese content and output without garbled code?

Define a byte array as large as the file to read all the bytes of the file at one time.

 

2. Directly reading all the file data into a byte array can avoid garbled code. Is there a problem?

If the file is too large, the byte array may cause memory overflow

 

  By:

  ● define a byte array as large as the file size, and then use the method of reading byte array to read it at one time.  

Method name explain
public int read(byte[] buffer) Each time a byte array is read, it returns - 1 if the byte is no longer readable

 

Mode 2:

● the official provides the following API for the byte input stream InputStream, which can directly read all the data of the file into a byte array  

Method name explain
public byte[] readAllBytes() throws IOException Directly load the byte data of the file object corresponding to the current byte input stream into a byte array
return

  [code example]

/**
   Target: use the file byte input stream to read all the bytes of the file at one time. Can solve the problem of garbled code.
 */
public class FileInputStreamDemo03 {
    public static void main(String[] args) throws Exception {
        // 1. Create a file byte input stream pipeline to connect with the source file
        File f = new File("file-io-app/src/data03.txt");
        InputStream is = new FileInputStream(f);

        // 2. Define a byte array just as large as the size of the file.
//        byte[] buffer = new byte[(int) f.length()];
//        int len = is.read(buffer);
//        System.out.println("how many bytes read:" + len);
//        System.out.println("file size:" + f.length());
//        System.out.println(new String(buffer));

        // Read all byte arrays
        byte[] buffer = is.readAllBytes();
        System.out.println(new String(buffer));

    }
}

 

4, Byte output stream: write byte data to file

File byte output stream: FileOutStream

Function: Based on memory, write out the data in memory to the disk file in the form of bytes.  

constructor explain
public FileOutputStream​(File file) Create a byte output stream pipeline to connect with the source file object
public FileOutputStream​(File file, boolean append) Create a byte output stream pipeline to connect with the source file object to append data
public FileOutputStream​(String filepath) Create a byte output stream pipeline to connect with the source file path
public FileOutputStream​(String filepath, boolean append) Create a byte output stream pipeline to connect with the source file path to append data

 

  The file byte output stream is an API for writing data  

Method name explain
public void write(int a) Write a byte out
public void write(byte[] buffer) Write a byte array
public void write(byte[] buffer , int pos , int len) Write a part of a byte array.

 

  Closing and refreshing of stream  

method explain
flush() Refresh the stream and continue to write data
close() Close the stream to release resources, but brush a new stream before closing. Once closed, no more data can be written

[code example]

public class OutputStreamDemo04 {
    public static void main(String[] args) throws Exception {
        // 1. Create a file byte output stream pipeline to connect with the target file
        OutputStream os = new FileOutputStream("file-io-app/src/out04.txt" , true); // Append data pipeline
//        OutputStream os = new FileOutputStream("file-io-app/src/out04.txt"); //  Clear the previous data first and write new data to enter

        // 2. Write data out
        // a.public void write(int a): write a byte
        os.write('a');
        os.write(98);
        os.write("\r\n".getBytes()); // Line feed
        // os.write('xu ')// [ooo]

        // b.public void write(byte[] buffer): write a byte array.
        byte[] buffer = {'a' , 97, 98, 99};
        os.write(buffer);
        os.write("\r\n".getBytes()); // Line feed

        byte[] buffer2 = "I am Chinese,".getBytes();
//        byte[] buffer2 = "I'm Chinese". getBytes("GBK");
        os.write(buffer2);
        os.write("\r\n".getBytes()); // Line feed


        // c. Public void write (byte [] buffer, int POS, int len): write a part of a byte array.
        byte[] buffer3 = {'a',97, 98, 99};
        os.write(buffer3, 0 , 3);
        os.write("\r\n".getBytes()); // Line feed

        // os.flush(); //  Write data must be refreshed, and the stream can continue to be used
        os.close(); // Release resources, including the of refresh! After closing, the flow cannot be used
    }
}

 

5, File copy

Copy sample drawing:

Case: file copy

Requirements:

● copy a video to "b.avi" in other directories

Idea:

① Create byte input stream object from data source

② Create byte output stream object based on destination

③ Read and write data, copy video

④ Release resources

[code example]

/**
 *   Objective: learn to use byte stream to complete file replication (support replication of all file types)
 */
public class CopyDemo05 {
    public static void main(String[] args) {
        try {
            // 1. Create a byte input stream pipeline to connect with the original video
            InputStream is = new FileInputStream("file-io-app/src/out04.txt");

            // 2. Create a byte output stream pipeline to connect with the target file
            OutputStream os = new FileOutputStream("file-io-app/src/out05.txt");

            // 3. Define a byte array to transfer data
            byte[] buffer = new byte[1024];
            int len; // Record the number of bytes read each time.
            while ((len = is.read(buffer)) != -1){
                os.write(buffer, 0 , len);
            }
            System.out.println("Copy complete!");

            // 4. Close the flow.
            os.close();
            is.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

 

Posted on Fri, 03 Dec 2021 10:24:47 -0500 by abduljan