[Yugong series] Java Teaching Course 53 stream byte reading and writing in January 2022

Article catalog

1, Byte stream

1. IO flow overview and classification

  • IO stream introduction
    • IO: input / output
    • Stream: an abstract concept, which is the general term for 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 replication; File upload; File download
  • 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
  • Usage scenarios of IO streams
    • If the operation is a plain text file, the character stream is preferred
    • If binary files such as picture, video and audio are operated, byte stream is preferred
    • If the file type is uncertain, byte stream is preferred Byte stream is a universal stream

2. Byte stream write data

  • 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 representing all classes of byte output stream

Subclass name features: subclass names are suffixed with their parent class name

  • Byte output stream

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

  • To write data using a byte output stream

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)

Call the write data method of byte output stream object

Free resources (close this file output stream and free any system resources associated with this stream)

  • Sample code
public class FileOutputStreamDemo01 {
    public static void main(String[] args) throws IOException {
        //Create byte output stream object
          /*
              Note:
                      1.If the file does not exist, it will be created for us
                      2.If the file exists, it will be emptied
          */
          //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");

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

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

3. Three ways to write data in byte stream

  • Classification of methods for writing data
  • Sample code
public class FileOutputStreamDemo02 {
    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
//        FileOutputStream fos = new FileOutputStream(new File("myByteStream\\fos.txt"));

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

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

        //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,0,bys.length);
        fos.write(bys,1,3);

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

4. Two small problems of byte stream writing data

  • How to wrap byte stream write data

windows:\r\n

linux:\n

  • mac:\
  • How to realize additional writing of byte stream write data

public FileOutputStream(String name,boolean append)

Creates a file output stream and writes 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
public class FileOutputStreamDemo03 {
    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();
    }
}

5. Byte stream write data plus exception handling

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
  • Sample code
public class FileOutputStreamDemo04 {
    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();
                }
            }
        }
    }
}

6. Byte stream read data (read one byte data at a time)

  • Byte input stream

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

  • To read data from a byte input stream

Create byte input stream object

Call the read data method of byte input stream object

Release resources

  • Sample code
public class FileInputStreamDemo01 {
    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();
    }
}

7. Byte stream copy file

  • Case requirements Copy "E:\itcast\mn.jpg" to "mn.jpg" under the module directory (the file can be any file)
  • Implementation steps
    • Copying a text file actually reads the contents of the text file from one file (data source) and then writes them to another file (destination)
    • Data source:
    • E:\itcast \ inside and outside the window txt - read data - InputStream - FileInputStream
    • destination:
    • myByteStream \ inside and outside the window txt - write data - OutputStream - FileOutputStream
  • code implementation
public class CopyTxtDemo {
    public static void main(String[] args) throws IOException {
        //Create byte input stream object from data source
        FileInputStream fis = new FileInputStream("E:\\itcast\\Inside and outside the window.txt");
        //Create byte output stream object based on destination
        FileOutputStream fos = new FileOutputStream("myByteStream\\Inside and outside the window.txt");

        //Read and write data, copy text files (read one byte at a time, write one byte at a time)
        int by;
        while ((by=fis.read())!=-1) {
            fos.write(by);
        }

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

8. Byte stream read data (read one byte array data at a time)

  • Method of reading one byte array at a time
    • 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
  • Sample code
public class FileInputStreamDemo02 {
    public static void main(String[] args) throws IOException {
        //Create byte input stream object
        FileInputStream fis = new FileInputStream("myByteStream\\fos.txt");

        byte[] bys = new byte[1024]; //1024 and its integer multiples
        int len;
      	//Cyclic reading
        while ((len=fis.read(bys))!=-1) {
            System.out.print(new String(bys,0,len));
        }

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

9. Byte stream copy file

  • Case requirements Copy "E:\itcast\mn.jpg" to "mn.jpg" under the module directory (the file can be any file)
  • Implementation steps
    • Create byte input stream object from data source
    • Create byte output stream object based on destination
    • Read and write data and copy pictures (read one byte array at a time and write one byte array at a time)
    • Release resources
  • code implementation
public class CopyJpgDemo {
    public static void main(String[] args) throws IOException {
        //Create byte input stream object from data source
        FileInputStream fis = new FileInputStream("E:\\itcast\\mn.jpg");
        //Create byte output stream object based on destination
        FileOutputStream fos = new FileOutputStream("myByteStream\\mn.jpg");

        //Read and write data and copy pictures (read one byte array at a time and write one byte array at a time)
        byte[] bys = new byte[1024];
        int len;
        while ((len=fis.read(bys))!=-1) {
            fos.write(bys,0,len);
        }

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

Added by superdude on Sat, 15 Jan 2022 14:36:32 +0200