Java learning phase I - 20 Java-Api02 IO stream file byte stream character stream

IO introduction

1 Stream

Before learning IO streams, the first concept we need to learn is Stream streams
In order to facilitate understanding, we can abstract the data reading and writing operation into data flowing in the "pipeline", but note:
1. Flow can only flow in one direction
2. The input stream is used to read → in
3. The output stream is used to write out → out
4. Data can only be read and written once from beginning to end
Therefore, from the perspective of the program, the input (read) / output (write) process of In/out relative to the program

2. Inheritance structure of IO stream

In java, the stream can be divided into byte stream and character stream according to different data units
Byte stream: for binary files
Character stream: for text files, it is easy to read and write garbled code. When reading and writing, it is best to specify the encoding set as UTF-8
In combination with the input and output directions of the corresponding types, the commonly used streams are:

File

Byte stream: for binary files

InputStream

FileInputStream
BufferedInputStream
ObjectInputStream

OutputStream

FileOutputStream
BufferedOutputStream
ObjectOutputStream

Character stream: for text files

Reader

FileReader
BufferedReader
InputStreamReader

Writer

FileWriter
BufferedWriter
OutputStreamWriter
PrintWriter writes line by line

3 File class

3.1 general

Encapsulates a disk path string on which one operation can be performed
You can encapsulate file paths, folder paths, and nonexistent paths

3.2 creating objects

File(String pathname) creates a new file instance by converting the given pathname string to an abstract pathname
new File("d:/abc/a.txt");
new File("d:/abc","a.txt");

3.3 common methods

3.4 exercise: Common test methods

Create package: CN tedu. file
Create class: testfile java

package cn.tedu.file;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
/*This class is used to test the File class File*/
public class TestFile {
    public static void main(String[] args) throws IOException {
        //1. Create a File object
        /*1.The argument to the constructor is pathname (pathname) of type String
        * This path can be a file path or a folder path*/
        /*2.\It has special meaning in the code, so if you want to really represent that this is a \, you need to escape with \*/
        //Note: here, you need to manually create 1.0 in the corresponding directory on disk D Txt and add content
        //Note: Create 1 Txt, you need to set the system display file suffix. If it is not set, the file name should be 1
        //Note: the file needs to import the package: import Java io. File;
        File file = new File("D:\\ready\\1.txt");
        //2. Common test methods
        //2.1 file and folder attribute test
        System.out.println(file.length());//12. Obtain the byte size of the specified file
        System.out.println(file.exists());//true to judge whether the specified file exists
        System.out.println(file.isFile());//true to judge whether the specified content is a file
        System.out.println(file.isDirectory());//false to judge whether the specified content is a folder
        System.out.println(file.getName());//1.txt to get the name of the specified content
        System.out.println(file.getParent());//D:\ready to get the parent of the specified content
        System.out.println(file.getAbsolutePath());//D:\ready.txt to get the absolute path of the specified content
        //2.2 create and delete
        file = new File("D:\\ready\\2.txt");
        /*If the folder specified to create the file does not exist, an error will be reported: Java io. IOException
        * The system cannot find the specified path. Because exceptions may occur, you need to throw an exception when calling */
        //Create a nonexistent file in windows 2 Txt, returns true successfully
        System.out.println(file.createNewFile());//true
        file = new File("D:\\ready\\m");
        System.out.println(file.mkdir());//true to create a nonexistent single-layer folder m
        file = new File("D:\\ready\\a\\b\\c");
        System.out.println(file.mkdirs());//true to create a non-existent multi-layer folder a/b/c
        System.out.println(file.delete());//c is deleted, files or empty folders are deleted
        file  = new File("D:\\ready\\a");
        System.out.println(file.delete());//false, because there is also directory b in directory a
        file  = new File("D:\\ready\\2.txt");
        System.out.println(file.delete());//true, delete 2 Txt file succeeded
        //2.3 document list test
        file = new File("D:\\ready");
        String[] listName = file.list();
        System.out.println(Arrays.toString(listName));
        File[] fs = file.listFiles();
        System.out.println(Arrays.toString(fs));
        System.out.println(fs[0].length());
    }
}

4-byte stream read

Byte stream is composed of bytes and character stream is composed of characters
In Java, a character consists of two bytes Byte stream is a basic stream, which is mainly used to process binary data.
Therefore, byte stream is commonly used, and can handle many different kinds of files, such as text document / audio / video, etc

4.1 InputStream abstract class

This abstract class is a superclass / abstract class representing all classes of byte input stream. Objects cannot be created

Common methods:
abstract int read() reads the next byte of data from the input stream
int read(byte[] b) reads a certain number of bytes from the input stream and stores them in buffer array B
int read(byte[] b, int off, int len) reads up to len data bytes in the input stream into the byte array, and off represents the offset at the time of storage
void close() closes this input stream and frees all system resources associated with the stream

4.2 FileInputStream subclass

Insert it directly into the file and read the file data directly

create object
FileInputStream(File file) - directly transfer file objects
Create a FileInputStream by opening a connection to the actual file. The file specifies the FileInputStream(String pathname) - path through the file object file in the file system
Create a FileInputStream by opening a connection to the actual file, which is specified by the pathname name in the file system

4.3 BufferedInputStream subclass

BufferedInputStream adds some functions to another input stream. When creating BufferedInputStream, an internal buffer array (default 8k size) will be created. When reading or skipping the bytes in the stream, the internal buffer can be filled again from the included input stream as needed, filling multiple bytes at a time.

create object
BufferedInputStream(InputStream in)
Create a BufferedInputStream and save its parameters, the input stream in, for future use.

4.4 exercise: byte stream reading case

Create package: CN tedu. file
Create class: testin java

package cn.tedu.file;
import java.io.*;
/*This class is used to practice byte input streams*/
public class TestIn {
    public static void main(String[] args) {
        //method();// Byte stream read
        method2();//Efficient byte stream reading
    }
    //This method is used to test the reading of efficient byte stream
    private static void method2() {
        //Define a local variable in that takes effect in this method. Pay attention to manual initialization and the value is null
        InputStream in = null;
        try {
            //1. Create efficient byte input stream object
//            InputStream in = new BufferedInputStream(
//                    new FileInputStream(new File("E:\\ready\\1.txt")));
              in = new BufferedInputStream
                      (new FileInputStream("E:\\ready\\1.txt"));
            //2. Read with stream
            int b;
            while ((b= in.read())!= -1){
                System.out.println(b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {//The flow closing operation is written in finally {}
            //3. Be sure to close the flow after it is used up!!!
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //This method is used to test the reading of byte stream
    private static void method() {
        //Create a local variable that takes effect in this method. Pay attention to manual initialization
        InputStream in = null;
        try {
            //1. Create byte input stream object for reading
            //InputStream in = new InputStream();// Error reason: abstract class cannot be instantiated
            //InputStream in = new FileInputStream(new File("E:\\ready\\1.txt"));
            in = new FileInputStream("E:\\ready\\1.txt");
            //2. Start reading
            /*read()Each call will read a byte. If the end of the data is read, it returns - 1*/
//            System.out.println(in.read());
//            System.out.println(in.read());
//            System.out.println(in.read());
//            System.out.println(in.read());
            //Requirement: all contents in the file need to be read circularly until it is finished
            //Define variables and record the read data
            int b;
            while((b=in.read())!= -1){
                System.out.println(b);
            }
        } catch (Exception e) {
            e.printStackTrace();//Print error message
        /*try-catch The third part of the structure: finally {}
        * This part is the code that will be executed no matter whether an exception is caught or not. It is often used to close the flow*/
        }finally {
            try {
                //3. Release resources. The stream resources must be released when they are used up!!!
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

5 character stream reading

Commonly used to process plain text data

5.1 Reader abstract class

Abstract class used to read character stream.

Common methods:
int read() reads a single character
int read(char[] cbuf) reads characters into an array
abstract int read(char[] cbuf, int off, int len) reads characters into a part of the array
int read(CharBuffer target) attempts to read characters into the specified character buffer
abstract void close() closes the stream and releases all resources associated with it

5.2 FileReader subclass

Convenient class for reading character files. The construction method of this class assumes that both the default character encoding and the default byte buffer size are appropriate. To specify these values yourself, you can first construct an InputStreamReader on the FileInputStream.

create object
FileReader(String fileName) creates a new FileReader given the filename from which the data is read
FileReader(File file) creates a new FileReader given the File from which to read data

5.3 BufferedReader subclass

Read the text from the character input stream and buffer each character, so as to realize the efficient reading of characters, arrays and lines.
You can specify the size of the buffer, or you can use the default size. In most cases, the default value is large enough.

create object
BufferedReader(Reader in) creates a buffered character input stream using the default size input buffer

5.4 exercise: character stream reading case

Create package: CN tedu. file
Create class: testin2 java

package cn.tedu.file;
import java.io.*;
/*This class is used to test the reading of character stream*/
public class TestIn2 {
    public static void main(String[] args) {
        //method();// Test normal character input stream
        method2();//Test efficient character input stream
    }
    //Create a method for testing efficient character input streams
    private static void method2() {
        //1. Define a local variable that takes effect in this method, and manually initialize the value null
        Reader in=null;
        try{
            //1. Create an efficient character reading stream object
            //in = new BufferedReader(new FileReader(new File("E:\\ready\\1.txt")));
            in = new BufferedReader(new FileReader("E:\\ready\\1.txt"));
            //2. Using flow objects
            int b;
            while((b=in.read())!=-1){
                System.out.println(b);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //3. Close the flow object
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //Create a method to test the normal character input stream
    private static void method() {
        //1.1 create a local variable that takes effect in this method. Note that the initialization value is null
        Reader in = null;
        try {
            //1.2 when creating a character input stream object, note that exceptions need to be caught
            //Reader in = new Reader();// Error reason: the abstract parent cannot be instantiated
            //in = new FileReader(new File("E:\\ready\\1.txt"));
            in = new FileReader("E:\\ready\\1.txt");
            //2. Using flow objects
            //System.out.println(in.read());
            //Requirement: read all contents in the file circularly. As long as it is not - 1, there is still data. Continue reading
            //3.1 define variables and record the read data
            int b;
            while((b = in.read())!= -1){
                System.out.println(b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {//3. Shut off
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

6-byte stream write out

6.1 OutputStream abstract class

This abstract class is a superclass that represents all classes of the output byte stream The output stream accepts the output bytes and sends them to a receiver

Common methods:
Void close() closes the output stream and frees all system resources associated with the stream
Void flush() flushes this output stream and forces all buffered output bytes to be written out
Void write (byte [] b) writes b.length bytes from the specified byte array to this output stream
Void write (byte [] B, int off, int len) writes len bytes from the offset off in the specified byte array to the output stream
Abstract void write(int b) writes the specified byte to this output stream

6.2 FileOutputStream subclass

Insert it directly into the file and write out the file data directly

Construction method (create object):
FileOutputStream(String name)
Creates a file output stream that writes data to a file with the specified name
FileOutStream(File file)
Creates a File output stream that writes data to the File represented by the specified File object
Fileoutstream (file, Boolean append) - if the second parameter is true, it means append and do not overwrite
Create a File output stream that writes data to the File represented by the specified File object. The following parameters refer to whether to overwrite the contents of the original File

6.3 BufferedOutputstream subclass

This class implements the buffered output stream. By setting this output stream, the application can write each byte to the underlying output stream without calling the underlying system every time for byte writing

Construction method (create object):
BufferedOutputStream(OutputStream out)
Create a new buffered output stream to write data to the specified underlying output stream

6.4 exercise: byte output stream test:

Create package: CN tedu. file
Create class: testout java

package cn.tedu.file;
import java.io.*;
/*This class is used to test byte output streams*/
public class TestOut {
    public static void main(String[] args) {
        method();//Used to test normal byte output stream
        //method2();// Used to test efficient byte output stream
    }
    //Create a method for testing efficient byte output streams
    private static void method2() {
        //1. Create a local variable that takes effect in this method. Pay attention to manual initialization
        OutputStream out = null;
        try{
            //2. Create efficient byte output stream object
//          out = new BufferedOutputStream(new FileOutputStream(new File("E:\\ready\\2.txt")));
            out = new BufferedOutputStream(new FileOutputStream("E:\\ready\\2.txt"));
            //3. Write out using stream object
            out.write(97);
            out.write(97);
            out.write(97);
        }catch (Exception e){
            e.printStackTrace();
        }finally {//The flow closing operation should be placed in finally {}
            try {
                //4. Shut off
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //Create a method to test the normal byte output stream
    private static void method() {
        //1. Create a local variable that takes effect in this method. Pay attention to manually initializing null
        OutputStream out = null;
        //2. Create a try catch finally structure because IO operations may generate exceptions
        try{
            //3. Create ordinary byte output stream object
            //out = new FileOutputStream(new File("E:\\ready\\2.txt"));
            //out = new FileOutputStream("E:\\ready\\2.txt");
            out = new FileOutputStream("E:\\ready\\2.txt",true);
            //4. Write out using stream object
            out.write(99);//Corresponding to a in ASCII code table
            out.write(99);//Corresponding to b in ASCII code table
            out.write(99);//Corresponding to c in ASCII code table
        }catch (Exception e){
            e.printStackTrace();
        }finally {//If you want the code to be executed, you need to write it in finally
            try {
                //5. Shut down operation
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

7 character stream write out

7.1 Writer abstract class

An abstract class that writes to a character stream

Common methods:
Abstract void close() closes the stream, but first refreshes it
Void write (char [] cbuf) writes to the character array
Void write(int c) writes a single character
Void write(String str) writes a string
Void write(String str,int off,int len) writes a part of a string
Abstract void write(char[] cbuf,int off,int len) writes to a part of the character array

7.2 FileWriter subclass

A convenience class for writing character files. The construction method of this class assumes that the default character encoding and default byte buffer size are acceptable If you need to customize these values yourself, you can first construct an OutputStreamWriter on FileOutputStream

Construction method (create object):
FileWriter(String filename)
Construct a FileWriter object according to the given file name
FileWriter(String filename,boolean append)
The FileWriter is constructed based on the given file name and a boolean value indicating whether to attach write data

7.3 BufferedWriter subclass

Writes text to the character output stream, buffering individual characters to provide efficient writing of individual characters, arrays, and strings You can specify the size of the buffer or accept the default size, which is large enough in most cases

Construction method (create object):
BufferedWriter(Writer out)
Create a buffered character output stream using the default size output buffer

7.4 exercise: character output stream test:

Create package: CN tedu. file
Create class: testout2 java

package cn.tedu.file;
import java.io.*;
/*This class is used to test character output streams*/
public class TestOut2 {
    public static void main(String[] args) {
        //method();// Output stream for testing normal characters
        method2();//Used to test efficient character output stream
    }
    //Create a method for testing efficient character output streams
    private static void method2() {
        //1. Create a local variable that takes effect in this method. The value is null. Pay attention to manual initialization!!!
        Writer out = null;
        //2. Because the program may throw exceptions, you need to write a try catch finally structure
        try{//Store code that may throw exceptions
            //3. Create ordinary character output stream object
            //out = new BufferedWriter(new FileWriter(new File("E:\\ready\\2.txt")));
            //out = new BufferedWriter(new FileWriter("E:\\ready\\2.txt"));
            out = new BufferedWriter(new FileWriter("E:\\ready\\2.txt",true));
            //4. Using flow objects
            out.write(100);
            out.write(100);
            out.write(100);
            out.write(100);
            out.write(100);
        }catch (Exception e){//Match and catch exceptions
            e.printStackTrace();//If an exception is caught, an error message is printed
        }finally {//The code block that must be executed is often used to close the flow
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //Create a method to test the normal character output stream
    private static void method() {
        //1. Create a local variable that takes effect in this method. The value is null. Pay attention to manual initialization!!!
        Writer out = null;
        //2. Because the program may throw exceptions, you need to write a try catch finally structure
        try{//Store code that may throw exceptions
            //3. Create ordinary character output stream object
            //out = new FileWriter(new File("E:\\ready\\2.txt"));
            //out = new FileWriter("E:\\ready\\2.txt");
            out = new FileWriter("E:\\ready\\2.txt",true);
            //4. Using flow objects
            out.write(98);
            out.write(98);
            out.write(98);
            out.write(98);
        }catch (Exception e){//Match and catch exceptions
            e.printStackTrace();//If an exception is caught, an error message is printed
        }finally {//The code block that must be executed is often used to close the flow
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

8 expansion

By learning the above streams, we can also expand and try to copy the following files:
Create package: CN tedu. file
Create class: testcopyfile java

package cn.tedu.file;
import java.io.*;
import java.util.Scanner;
/*This class is used to expand exercises and copy cases*/
public class TestCopyFile {
    public static void main(String[] args) {
        //1. Prompt and receive the source file path and target location path entered by the user
        System.out.println("Please enter the source file path:");
        String f = new Scanner(System.in).nextLine();//--Copy what
        System.out.println("Please enter the destination file path:");
        String t = new Scanner(System.in).nextLine();//--Copy to where
        //2. Call the method of copying files using character stream and pass in the two parameters just received
        //ZFCopy(f,t);
        //3. Call the method of copying files using byte stream and pass in the two parameters just received
        ZJCopy(f,t);
    }
    //Create a method to copy files using byte stream. Pay attention to two parameters
    private static void ZJCopy(String f, String t) {
        //1. Define local variables that take effect in the whole method. Pay attention to manual initialization, and the value is null
        InputStream in = null;
        OutputStream out = null;
        //2. Since the code may throw exceptions, you need to complete the try catch finally structure
        try{
            //3.1 create an efficient byte input stream, and the incoming parameter is the path of the target file
            in = new BufferedInputStream(new FileInputStream(f));
            //3.2 create an efficient byte output stream. The passed in parameter is the path to which the target file is copied
            out = new BufferedOutputStream(new FileOutputStream(t));
            //4. After you get the flow object, you can do specific business operations
            //4.1 define variables to record read data
            int b ;
            //4.2 use the loop to read the target file until the return value is - 1. When there is no data, the loop ends
            while((b = in.read())!=-1){//Read the contents of the source file
                out.write(b);//Write out the contents read in this cycle to the file in the specified location
            }
            System.out.println("Congratulations! File copied successfully!");
        }catch(Exception e){
            System.out.println("I'm sorry! File copy failed!");
            e.printStackTrace();
        }finally {//The code that must be executed needs to be put in finally, such as flow closing operation
            /*Closed flows are sequential: if there are multiple flows, the last created flow is closed first
             * Multiple related flow statements need their own try catch*/
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //Create a method to copy files using character streams. Note: copying requires two stream objects
    private static void ZFCopy(String f, String t) {
        //1. Define local variables that take effect in the whole method. Pay attention to manual initialization, and the value is null
        Reader in = null;
        Writer out = null;
        //2. Since the code may throw exceptions, you need to complete the try catch finally structure
        try{
            //3.1 create an efficient character input stream, and the passed in parameter is the path of the target file
            in = new BufferedReader(new FileReader(f));
            //3.2 create an efficient character output stream. The passed in parameter is the path to which the target file is copied
            out = new BufferedWriter(new FileWriter(t));
            //4. After you get the flow object, you can do specific business operations
            //4.1 define variables to record read data
            int b ;
            //4.2 use the loop to read the target file until the return value is - 1. When there is no data, the loop ends
            while((b = in.read())!=-1){//Read the contents of the source file
                out.write(b);//Write out the contents read in this cycle to the file in the specified location
            }
            System.out.println("Congratulations! File copied successfully!");
        }catch(Exception e){
            System.out.println("I'm sorry! File copy failed!");
            e.printStackTrace();
        }finally {//The code that must be executed needs to be put in finally, such as flow closing operation
            /*Closed flows are sequential: if there are multiple flows, the last created flow is closed first
            * Multiple related flow statements need their own try catch*/
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

9 summary: inheritance structure of IO

1. Mainstream classification

  1. Classification by direction: input stream output stream (relative to the program, writing data from the program to the file is output)
  2. Classified by transport type: byte stream character stream
  3. Combination: byte input stream byte output stream character input stream character output stream

2. Learning methods: learn general methods in the abstract parent class and how to create objects in the child class
3. Byte input stream:

The InputStream abstract class cannot be new. It can be used as a superclass to learn the common methods it provides
--FileInputStream Subclass,Byte input stream of operation file,General class
--BufferedInputStream Subclass,Buffered byte input stream,General class

4. Character input stream

The Reader abstract class cannot be new. It can be used as a superclass to learn the common methods it provides
--FileReader,Subclass,Character input stream of operation file,General class
--BufferedReader,Subclass,Buffered character input stream,General class

5. Byte output stream:

The OutputStream abstract class cannot be new. It can be used as a superclass to learn the common methods it provides
--FileOutputStream Subclass,Byte output stream of operation file,General class
--BufferedOutputStream Subclass,Buffer byte output stream,General class

6. Character output stream

The Writer abstract class cannot be new. It can be used as a superclass to learn the common methods it provides
--FileWriter,Subclass,Character output stream of operation file,General class
--BufferedWriter,Subclass,Buffered character output stream,General class

Keywords: Java

Added by monkeymade on Wed, 19 Jan 2022 08:19:27 +0200