Java IO byte stream

1. IO flow

1.1 IO flow overview and classification

1. Introduction to IO flow

  • IO: input / output
  • Stream: it is an abstract concept, which is the general name of data transmission. In other words, the transmission of data between devices is called stream, and the essence of stream is data transmission
  • IO stream is used to deal with data transmission between devices.
  • Common applications: file copy, file upload, file download

2. Classification of IO streams

  • According to the flow direction of data
    • Input stream: reading data
    • Output stream: write data
  • By data type
    • Byte stream
      • Byte input stream byte output stream
    • Character stream
      • Character input stream character output stream

3. Usage scenario of IO stream

  • If the operation is a plain text file, the character stream is preferred
  • If the operation is a binary file such as picture, video and audio. Byte stream is preferred
  • If the file type is uncertain, byte stream is preferred. Byte stream is a universal stream

1.2 byte stream write data

1. Byte stream abstract base class

  • InputStream: this abstract class is a superclass that represents all classes of byte input stream-
  • OutputStream: this abstract class is a superclass that represents all classes of byte output stream
  • Characteristics of subclass Name: subclass names are suffixed with their parent class name

2. Byte output stream

  • FileOutputStream(String name): creates a file output stream and writes it to the file with the specified name

3. Steps of using byte output stream to write data

  1. Create a byte output stream object (call the system function to create a file, create a byte output stream object, and let the byte output stream object point to the file)
  2. Call the write data method of byte output stream object
  3. Free resources (close this file output stream and free any system resources associated with this stream)

4. Example code

import java.io.FileOutputStream;
import java.io.IOException;

public class Demo {
    public static void main(String[] args) throws IOException {
        //Create byte output stream object
        //FileOutputStream(String name): creates a file output stream and writes it to the file with the specified name
        FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt");
        
        /*
        Three things were done:
        A:The system function is called to create the file
        B:Created byte output stream object
        C:Let the byte output stream object point to the created file
        */
    
        //void write(int b): writes the specified bytes to this file output stream
        fos.write(97);

        //Finally, we should release resources
        //void close(): closes the file output stream and frees any system resources associated with the stream.
        fos.close();
    }
}

1.3 three ways to write data in byte stream

1. Classification of data writing methods

Method nameexplain
void write(int b)Writes the specified bytes to this file. The output stream writes one byte of data at a time
void write(byte[] b)Write b.length bytes from the specified byte array to this file. The output stream writes byte array data one at a time
void write(byte[] b, int off, int len)Write len bytes to this file from the specified byte array and offset o ff. The output stream writes part of the data of one byte array at a time

2. Sample code

import java.io.FileOutputStream;
import java.io.IOException;

public class Demo {
    public static void main(String[] args) throws IOException {

        //FileOutputStream(String name): creates a file output stream and writes it to the file with the specified name
        FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt");

        //FileOutputStream(File file): creates a File output stream to write to the File represented by the specified File object
        // File file = new File("myByteStream\\fos.txt");

        //void write(int b): writes the specified bytes to this file output stream
        // fos.write(97);

        // void write(byte[] b): writes b.length bytes from the specified byte array to the output stream of this file
        // byte[] bys = {97, 98, 99, 100, 101};
        
        //byte[] getBytes(): returns the byte array corresponding to the string
        byte[] bys = "abcde".getBytes();

        //void write(byte[] b, int off, int len): write len bytes to the file output stream starting from the specified byte array and starting from offset off
        fos.write(bys,1,3);

        //Release resources
        fos.close();
    }
}

3.4 two small problems of byte stream writing data

1. How to wrap byte stream write data

  • windows:\r\n
  • linux:\n
  • mac:\r

2. How to realize additional writing of byte stream write data

  • public FileOutputStream(String name,boolean append)
  • Create a file output stream and write to the file with the specified name. If the second parameter is true, the bytes are written to the end of the file instead of the beginning sample code

3. Example code

import java.io.FileOutputStream;
import java.io.IOException;

public class Demo {
    public static void main(String[] args) throws IOException {

        //Create byte output stream object
        // FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt");
        FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt", true);
        
        //Write data
        for (int i = 0; i < 10; i++) {
            fos.write("hello".getBytes());
            fos.write("\r\n".getBytes());
        }
        
        //Release resources
        fos.close();
    }
}

Data stream write exception processing

1. Exception handling format

  • try-catch-finally
try{
	Possible exception codes;
}catch(Exception class name variable name){
	Exception handling code;
}finally{
	Perform all cleanup operations;
}
  • finally features
    • Statements that are finally controlled must be executed unless the JVM exits

2. Sample code

import java.io.FileOutputStream;
import java.io.IOException;

public class Demo {
    public static void main(String[] args) {
        
        //Join finally to release resources
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("myByteStream\\fos.txt");
            fos.write("hello".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

3.6 byte stream read data (read data by byte)

1. Byte input stream

  • FileInputStream(String name): create a FileInputStream by opening the connection with the actual file, which is named by the pathname in the file system

2. Steps of reading data from byte input stream

  • Create byte input stream object
  • Call the read data method of byte input stream object
  • Release resources

3. Example code

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

public class Demo {
    public static void main(String[] args) throws IOException {

        //Create byte input stream object
        //FileInputStream(String name)
        FileInputStream fis = new FileInputStream("myByteStream\\fos.txt");
        int by;

        /*
        fis.read(): Read data
        by=fis.read(): Assign the read data to by
        by != -1: Judge whether the read data is - 1
        */

        while ((by=fis.read())!=-1) {
            System.out.print((char)by);
        }

        //Release resources
        fis.close();
    }
}

3.7 byte stream read data (read data by byte array)

1. Method of reading data from byte array

  • public int read(byte[] b): read up to b.length bytes of data from the input stream
  • Returns the total number of bytes read into the buffer, that is, the actual number of bytes read

2. Example code:

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

public class Demo {
    public static void main(String[] args) throws IOException {
        
        //Create byte input stream object
        FileInputStream fis = new FileInputStream("myByteStream\\fos.txt");
        
        /*
        hello\r\n
        world\r\n
        First time: hello
        Second time: \ r\nwor
        Third time: ld\r\nr
        */
        
        byte[] bys = new byte[1024]; //1024 and its integer multiples
        int len;
        while ((len=fis.read(bys))!=-1) {
            System.out.print(new String(bys,0,len));
        }
        
        //Release resources
        fis.close();
    }
}

Keywords: Java Back-end

Added by qt4u on Sun, 13 Feb 2022 09:11:31 +0200