Java IO stream --- byte stream

Keywords: Java Back-end

IO stream

1, IO stream overview and classification

IO stream introduction

  • 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 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 (Reader)
    Character output stream (Writer)

Usage scenarios of IO streams

  • 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

Today we are mainly talking about byte stream, and character stream will be explained in the next article

2, Byte output stream

Three ways to write data in byte stream

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 byte at a time
void write(byte[] b, int off, int len)Write len bytes to this file from the specified byte array and offset off. The output stream writes part of the data of the byte array one at a time

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");
        //new File(name)
//        FileOutputStream fos = new FileOutputStream(new File("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");
//        FileOutputStream fos2 = new FileOutputStream(file);
//        FileOutputStream fos2 = 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();
    }
}

Two small problems in writing data from byte stream

How to wrap byte stream write data

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

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();
    }
}

3, Byte input stream

Byte stream read data
We experience the operation of reading data through two cases
1. Byte stream read data (read one byte at a time)
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\xxx.txt - read data - InputStream - FileInputStream. We read a TXT file from the itcast file on disk E.

  • destination:

    myByteStream\xxx.txt - write data - OutputStream - FileOutputStream. Write the read data to the txt document under the myByteStream module

Sample code

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\\xxx.txt");
        //Create byte output stream object based on destination
        FileOutputStream fos = new FileOutputStream("myByteStream\\xxx.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();
    }
}

2. Byte stream read data (read one byte array at a time)
If we need to read byte arrays one at a time, we need to know how to read byte arrays one at a time

public int read(byte[] b)	//Read up to b.length bytes of data from the input stream

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");

        /*
            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();
    }
}

Now that we know the byte stream, let's look at its extension, byte buffer stream

4, Byte buffer stream

BufferOutputStream: by setting such an output stream, an application can write bytes to the underlying output stream without causing a call to the underlying system for each byte written
BufferedInputStream: when bytes are read or skipped from the stream, the internal buffer will be refilled from the included input stream as needed, many bytes at a time
Construction method of byte buffer stream

Method nameexplain
BufferedOutputStream(OutputStream out)Create byte buffered output stream object
BufferedInputStream(InputStream in)Create byte buffered input stream object

Sample code

public class BufferStreamDemo {
    public static void main(String[] args) throws IOException {
        //Byte buffered output stream: BufferedOutputStream(OutputStream out)
 
        BufferedOutputStream bos = new BufferedOutputStream(new 				                                       FileOutputStream("myByteStream\\bos.txt"));
        //Write data
        bos.write("hello\r\n".getBytes());
        bos.write("world\r\n".getBytes());
        //Release resources
        bos.close();
    

        //Byte buffered input stream: BufferedInputStream(InputStream in)
        BufferedInputStream bis = new BufferedInputStream(new                                                          FileInputStream("myByteStream\\bos.txt"));

        //Read one byte of data at a time
//        int by;
//        while ((by=bis.read())!=-1) {
//            System.out.print((char)by);
//        }

        //Read one byte array data at a time
        byte[] bys = new byte[1024];
        int len;
        while ((len=bis.read(bys))!=-1) {
            System.out.print(new String(bys,0,len));
        }

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

Posted by SammyGunnz on Fri, 12 Nov 2021 17:18:42 -0800