java basic io stream: the story of OutputStream and InputStream

io flow overview:

IO flow is used to process data transmission between devices, upload files and download files. Java operates on data through flow. The objects Java uses to operate flow are all in io package.

IO flow classification

According to data flow direction

Input stream read in data

Output stream writes out data

By data type

Byte stream

Character stream

What kind of flow is used in what situations?

If the file where the data is located is opened through Notepad provided by windows and can read the contents, character stream is used, and byte stream is used for others.

If you don't know anything, use a byte stream.

IO stream common base class

Abstract base class of byte stream:

InputStream ,OutputStream.

Abstract base class of character stream:

Reader , Writer.

Note:
The names of subclasses derived from these four classes are suffixes with the names of their parents as subclass names.
For example: FileInputStream, a subclass of InputStream.
For example: the subclass FileReader of Reader.

Subclass FileOutputStream of OutputStream

Construction method:

FileOutputStream(File file)

FileOutputStream(String name)

The second construction method is recommended:

FileOutputStream outputStream = new FileOutputStream("a.txt");

Several things have been done to create the byte output stream object:

A: Calling system functions to create files
B: Create outputStream object
C: Point the foutputStream object to this file

Write data to text through byte output stream

public void write(int b)
public void write(byte[] b)
public void write(byte[] b,int off,int len)

As you can see from the method, it can only be written in bytes

outputStream.write("hello".getBytes()); Appears in text hello
outputStream.write(96)  //a appears in the text

byte[] bys={97,98,99,100,101};
outputStream.write(bys,1,3); Appears in text bcd

In this way, the data in the text will not be wrapped or appended, and each write will overwrite the original.

Append:

FileOutputStream outputStream = new FileOutputStream("a.txt",true);//The second parameter, true, is set to appendable.

Line feed \ n\r:

for (int i = 0; i <5 ; i++) {
    outputStream.write("hello".getBytes());
    outputStream.write("\n\r".getBytes());
}

Note: remember to turn off when running out.

outputStream.close();

Complete example:

package io2;

import java.io.FileOutputStream;
import java.io.IOException;
/**
 * new FileOutputStream("a.txt",true);  The second parameter, true, is set to splice the written data at the end
 * \n\r Line feed
 * write(bys,1,3);  Write byte array
 */
public class out {
    public static void main(String args[]){
        FileOutputStream outputStream = null;
        try {
            //FileOutputStream fos = new FileOutputStream(file);
            outputStream = new FileOutputStream("a.txt",true);
            /*
             * Several things have been done to create the byte output stream object:
             * A:Calling system functions to create files
             * B:Create outputStream object
             * C:Point the foutputStream object to this file
             */

//            for (int i = 0; i <5 ; i++) {
//                outputStream.write("hello".getBytes());
//                outputStream.write("\n\r".getBytes());
                  
//            }
            byte[] bys={97,98,99,100,101};
            outputStream.write(bys,1,3);
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}

Subclass FileInputStream of InputStream

The construction method of FileInputStream

FileInputStream(File file)
FileInputStream(String name)

The second construction method is recommended:

FileInputStream inputStream = new FileInputStream("a.txt");

Now read the data just written to the console:

public int read()
public int read(byte[] b)

The first read is to read a byte, and the second read is to read an array of bytes.

//Read a byte
int by = 0;
while ((by=inputStream.read())!=-1){
      System.out.println((char)by);
}

If there is no data, return - 1, which is used to judge whether the reading is finished.

//Read a byte array, generally 1024
int len = 0 ;
byte[] bys = new byte[1024];
while ((len = inputStream.read(bys)) != -1) {
    System.out.println(new String(bys,0,len));
}

The return values of the two reads are slightly different. read() returns the bytes read and - 1 at the end of the read. read(byte[] b) returns the number of bytes read. The bytes read are placed in the bytes array and - 1 is returned when no data is found at the end of the read.

Two reading modes are illustrated:

The same run out of streams, but also to close in time to prevent the occupation of memory.

inputStream.close();

Complete example:

It is recommended to read data as an array of bytes.

package io2;

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

/**
 * Create by stefan
 * Date on 2018-05-27  23:00
 * Convertion over Configuration!
 */
public class input2 {
    public static void main(String args[]){
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream("a.txt");
//            byte[] bys = new byte[4];
//            int len = inputStream.read(bys);
//            System.out.println(new String(bys));  //bcd
//            System.out.println(len);  //3
//            System.out.println(inputStream.read(bys));  //-1
            int len = 0 ;
            byte[] bys = new byte[1024];
            while ((len = inputStream.read(bys)) != -1) {
                System.out.println(new String(bys,0,len));
            }
            /**
             *    public String(byte bytes[]) {
             this(bytes, 0, bytes.length);
             }
             */

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

Byte stream copy file

Use the input stream to read the bytes in one file, and then use the output stream to write the bytes read out to another file (it will be created automatically if it does not exist)

package io2;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

/**
 * Create by stefan
 * Date on 2018-05-27  23:19
 * Convertion over Configuration!
 */
public class copy {
    public static void main(String args[]) throws IOException {
        FileInputStream inputStream = new FileInputStream("E:\\huge1.jpg");
        FileOutputStream outputStream = new FileOutputStream("E:\\Gu Yue.jpg");
        
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len=inputStream.read(bytes)) != -1) {
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        inputStream.close();
        outputStream.close();
    }
}

Note: copy text, picture, mp3, video, etc. in the same way.

The speed of byte stream reading and writing an array at a time is much faster than that of reading and writing a byte at a time. This is the buffer effect of adding an array.

When java itself is designed, it also takes such a design idea into consideration (explained later in decoration design mode), so it provides byte buffer stream.

Byte buffered output stream
BufferedOutputStream
Byte buffered input stream
BufferedInputStream

BufferedOutputStream

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("a.txt",true));
bos.write("hello world".getBytes());
bos.close();

BufferedInputStream

BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a.txt"));
byte[] bytes = new byte[1024];
int len = 0;
while ((len=bis.read(bytes)) != -1) {
    System.out.println(new String(bytes,0,len));
}
bis.close();

Note:

  • The function of byte buffer stream is to improve the efficiency of input and output.
  • The constructor can specify the buffer size, but we usually don't use it, because the default buffer size is enough.
  • Why not pass a specific file or file path, but an OutputStream object? The reason is very simple, the byte buffer stream only provides buffer, which is designed for efficiency. However, the real read-write operation depends on the basic stream object.

Upgrade of copied files:

BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\modern-java.pdf"));
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("F:\\Steamed Bun Stuffed with Juicy Pork\\Mogao bus\\modern-java.pdf"));
int len = 0;
byte[] bytes =new byte[1024];
while ((len=bis.read(bytes)) != -1) {
    bos.write(bytes,0,len);
    bos.flush();
}
bis.close();
bos.close();

Test: the efficiency of four kinds of copying files

package io2;

import java.io.*;

/**
 *
 * Time to test replication
 * Create by stefan
 * Date on 2018-05-28  10:28
 * Convertion over Configuration!
 */
public class copy2 {
    //Byte by byte replication, 22697 MS
    public static  void  fun() throws IOException {
        FileInputStream fis = new FileInputStream("F:\\Steamed Bun Stuffed with Juicy Pork\\Mogao bus\\modern-java.pdf");
        FileOutputStream fos = new FileOutputStream("E:\\modern-java.pdf");
        int by = 0;
        while ((by=fis.read()) != -1) {
            fos.write(by);
            fos.flush();
        }
        fis.close();
        fos.close();
    }
    //1024 byte array replication takes 63 MS
    public  static void  fun1() throws IOException {
        FileInputStream fis = new FileInputStream("F:\\Steamed Bun Stuffed with Juicy Pork\\Mogao bus\\modern-java.pdf");
        FileOutputStream fos = new FileOutputStream("E:\\modern-java.pdf");
        int len = 0;
        byte[] bytes =new byte[1024];
        while ((len=fis.read(bytes)) != -1) {
            fos.write(bytes,0,len);
            fos.flush();
        }
        fis.close();
        fos.close();
    }
    // Byte by byte replication, but it takes 64 milliseconds to use the buffer stream
    public static   void  fun2() throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\modern-java.pdf"));
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("F:\\Steamed Bun Stuffed with Juicy Pork\\Mogao bus\\modern-java.pdf"));
        int by = 0;
        while ((by=bis.read()) != -1) {
            bos.write(by);
            bos.flush();
        }
        bis.close();
        bos.close();
    }
    // 1024 byte array copied and buffered in 7 ms
    public  static void  fun3() throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\modern-java.pdf"));
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("F:\\Steamed Bun Stuffed with Juicy Pork\\Mogao bus\\modern-java.pdf"));
        int len = 0;
        byte[] bytes =new byte[1024];
        while ((len=bis.read(bytes)) != -1) {
            bos.write(bytes,0,len);
            bos.flush();
        }
        bis.close();
        bos.close();
    }

    public static void main(String args[]) throws IOException {
        long t1 = System.currentTimeMillis();
        fun3();
        long t2 = System.currentTimeMillis();
        System.out.println(t2-t1);
    }

}

The test results show that:
1024 byte arrays are copied and buffered for maximum efficiency.

java basic io stream -- File advertisement (revisit Classic)

java basic io stream: the story of OutputStream and InputStream

java basic io stream -- the change of character stream

java basic io flow -- supporting role is also popular

Tags: Programming Java Windows

Posted on Wed, 15 Apr 2020 02:54:02 -0700 by powergen