IO stream: byte stream

Keywords: Java ascii Windows Linux

IO flow overview

IO flow is used to process data transmission between devices. Java operates on data through flow. The objects Java uses to operate flow are all in io package.
Classification of IO streams
Divided into input flow and output flow according to data flow direction
By data type: byte stream, character stream
Byte stream can read and write any type of file, such as audio, video, text.
Character streams can only read and write text files.

Abstract base class of byte stream: InputStream (input), OutputStream (output)
Abstract base classes for character streams: Reader, Writer
The subclasses derived from these four classes all use the name of the parent class as the suffix, and different subclass names represent operations on different data.
FileOutputStream, FileInputStream. And the input and output (read and write) appear in pairs.

Byte stream

FileOutputStream

FileOutputStream: a File output stream that writes data to the output stream of a File or FileDescriptor.

Construction method

public FileOutputStream(File file) throws FileNotFoundException
Creates a File output stream that writes data to the File represented by the specified File object. Create a new FileDescriptor object to represent this File connection.
public FileOutputStream(String name) throws FileNotFoundException
Creates an output file stream that writes data to a file with the specified name. Create a new FileDescriptor object to represent this file connection.

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

public class Demo {
    public static void main(String[] args) throws IOException {
        File file = new File("a.txt");
        //If the file associated with the output stream does not exist, it is created automatically
        FileOutputStream outputStream = new FileOutputStream(file);

        FileOutputStream outputStream1 = new FileOutputStream("b.txt");
		//The close method is used to close the flow. Every flow created needs to be closed at the end
		/*Effect:
		1.Notify the system to release the resources (release resources) from the relationship management a.txt file.
		2.Make the stream object garbage and wait for the garbage collector to recycle.*/
        outputStream.close();
        outputStream1.close();       
    }
}

The process of creating a byte output stream object

  1. Call system resource to create a.txt file (if the file does not exist)
  2. Create an outputStream object
  3. Point the outputStream object to this file

In the above two construction methods, you can also pass in the second boolean type parameter append, which will be explained later

Method

public void write(int b) throws IOException
Writes the specified bytes to this file output stream.
public void write(byte[] b) throws IOException
Writes b.length bytes from the specified byte array to the output stream of this file.
public void write(byte[] b,int off,int len) throws IOException
Writes len bytes in the specified byte array starting from offset off to the output stream of this file.

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

public class Demo {
    public static void main(String[] args) throws IOException {
        FileOutputStream out = new FileOutputStream("a.txt");

        //The write method writes data to this file output stream
        /*If 0-127 is passed in, the content corresponding to the ASCII code table will be written into the text
        If a number outside this range is passed in, an error will not be reported, but it will be written*/
        out.write(97);
        String str="Fight the epidemic, come on, Wuhan";
        byte[] bytes = str.getBytes();
        out.write(bytes);
        //For line wrap
        out.write("\r\n".getBytes());
        //In UTF-8, one Chinese character takes up three bytes. To write the anti epidemic situation, you need to write 12 bytes from 0
        out.write(bytes,0,12);
        
        out.close();
    }
}

In Windows system, it means line break; in Linux system, it means line break; in Mac system, it means line break.

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

public class Demo {
    public static void main(String[] args) throws IOException {
    	//In the construction method, the parameter append can be passed in to decide whether to overwrite or renew the original data
    	//Pass in true for renewal, pass in false for overwrite
        FileOutputStream out = new FileOutputStream("a.txt",true);

        out.write("Go China!".getBytes());

        out.close();
    }

Exception handling of flow
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo4 {
    public static void main(String[] args) {
        FileOutputStream out=null;
        try {
            out=new FileOutputStream("a.txt");
            out.write("abcd".getBytes());
        }
        catch (IOException e){
            e.printStackTrace();
        }
        finally {
        //Close resource out.close(); in finally
            try {
            /*If an exception occurs when or before the FileOutputStream object is created, resulting in the object not being created successfully, you do not need to close the resource
            Therefore, if is needed to determine whether the stream object is empty*/
                if (out!=null)
                    out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
FileInputStream

FileInputStream is used to read raw byte streams such as image data.

Construction method

public FileInputStream(File file) throws FileNotFoundException
Create a FileInputStream by opening a connection to the actual file specified by the file object file in the file system. Create a new FileDescriptor object to represent this file connection.
public FileInputStream(String name) throws FileNotFoundException
Create a FileInputStream by opening a connection to the actual file specified by the pathname name in the file system. Create a new FileDescriptor object to represent this file connection.

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

public class Demo {
    public static void main(String[] args) throws IOException {
        //If the file associated with the input stream does not exist, an error will be reported.
        File file = new File("b.txt");
        FileInputStream in1 = new FileInputStream(file);

        FileInputStream in2 = new FileInputStream("b.txt");

        in1.close();
        in2.close();
    }
}
Method

public int read() throws IOException
Read a data byte from this input stream.
public int read(byte[] b) throws IOException
Read up to b.length bytes of data into a byte array from this input stream.
public int read(byte[] b,int off,int len) throws IOException
Read up to len bytes of data into a byte array from this input stream.

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

public class Demo {
    public static void main(String[] args) throws IOException {
    	//b. The data in txt is abcd.
        FileInputStream in = new FileInputStream("b.txt");
        //One byte of ASCII code is returned at a time, and - 1 is returned after reading
        int b1 = in.read();
        System.out.println(b1);
        int b2 = in.read();
        System.out.println(b2);
        int b3 = in.read();
        System.out.println(b3);
        int b4 = in.read();
        System.out.println(b4);
        int b5 = in.read();
        System.out.println(b5);

        in.close();
    }
}
/*
Operation result:
97
98
99
100
-1
*/
public class Demo {
    public static void main(String[] args) throws IOException {
        FileInputStream in = new FileInputStream("b.txt");

        byte[] bytes = new byte[1024];
        //Read the data in the file into a byte array.
        //Returns the number of valid bytes read
        int len = in.read(bytes);
        System.out.println(len);
		
		//a, b, c and d are respectively stored in the 0 ~ 3 index of array bytes
        String str = new String(bytes,0,len);
        System.out.println(str);

        in.close();

    }
}
/*
Operation result:
4
abcd
*/
/*,
b - Buffer to store read data.
off - Start offset in destination array b.
len - The maximum number of bytes read.
*/
import java.io.FileInputStream;
import java.io.IOException;

public class Demo {
    public static void main(String[] args) throws IOException {
        FileInputStream in = new FileInputStream("b.txt");

        byte[] bytes = new byte[1024];
        //From the beginning of the file, read the len length bytes to the array, and store them at the off index of the array
        //If off is 2, a, b, c are stored from the 2 index of the bytes array. So generally, off is 0.
        int len = in.read(bytes, 0, 3);
        System.out.println(len);

		//Document
        String str = new String(bytes, 0, len);
        System.out.println(str);

        in.close();
    }
}
/*
Operation result:
3
abc
*/
Byte stream copy file
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo {
    public static void main(String[] args) throws IOException {
        //Create input stream, associate source file
        FileInputStream inputStream = new FileInputStream("a.txt");
        //Create output stream, associate target file
        FileOutputStream outputStream = new FileOutputStream("C:\\Users\\Peng Yang\\Desktop\\aCopy.txt");
        int b=0;    //Used to receive bytes read
        while ((b=inputStream.read())!=-1){
            outputStream.write(b);
        }
        //Release resources
        inputStream.close();
        outputStream.close();
    }
}

In general, there are many bytes in a file. If we only read one byte at a time, the speed is very slow. We can read one byte array at a time to improve efficiency

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

public class Demo {
    public static void main(String[] args) throws IOException {
        FileInputStream in = new FileInputStream("a.txt");
        FileOutputStream out = new FileOutputStream("C:\\Users\\Peng Yang\\Desktop\\aCopy.txt");

		//Create an array to act as a buffer, the general size is 8kb, which can be determined according to the actual situation
        byte[] bytes=new byte[1024*8];
        int len=0;  //Record the number of valid bytes per read
        while((len=in.read(bytes))!=-1){
        	//If the write length len is not set, if the number of valid bytes read last time is less than the array length, the extra bytes will be copied to the file
            out.write(bytes,0,len);
        }

        in.close();
        out.close();
    }
}
BufferedOutputStream&BufferedInputStream

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 effect of adding a buffer such as an array. java also takes this design idea into account when designing, so it provides a byte buffer stream.
BufferedOutputStream
This class implements buffered output streams. By setting this output stream, the application can write individual bytes to the underlying output stream without having to call the underlying system for each byte write.
BufferedInputStream
When you create a BufferedInputStream, an internal array of buffers is created. When reading or skipping bytes in a stream, the internal buffer can be filled again from the contained input stream as needed, filling multiple bytes at a time. Mark operation records a point in the input stream. reset operation enables to read all bytes read since the last mark operation again before obtaining new bytes from the included input stream.

Copy file

public BufferedOutputStream(OutputStream out)
Creates a new buffered output stream to write data to the specified underlying output stream.
public BufferedInputStream(InputStream in)
Create a BufferedInputStream and save its parameters, input stream in, for future use.

import java.io.*;

public class Demo {
    public static void main(String[] args) throws IOException {
        BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream("a.txt"));
        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream("b.txt"));

        int b=0;
        while ((b=inputStream.read())!=-1){
            outputStream.write(b);
        }

        inputStream.close();
        outputStream.close();
    }
}

When creating the BufferedInputStream object, a buffer array will be created. The bytes read will be stored in the buffer array first, and then written to the file,
So it is almost as efficient to read one byte at a time as to define a buffer array to store the read elements.
So when using BufferedOutputStream and BufferedInputStream to copy files, there is no need to define a buffer array.
When using FileInputStream and FileOutputStream to copy files, the efficiency of self defining buffer array is similar to that of using BufferedOutputStream and BufferedInputStream.

Published 33 original articles, won praise 1, visited 546
Private letter follow

Posted by colake on Thu, 20 Feb 2020 03:47:00 -0800