java zero foundation II -- 10 IO stream

Connect video



1, Basic use of documents

file

What is a file

Files are not unfamiliar to us. Files are places to save data, such as word documents, txt files, excel files... All of which are files. It can save a picture, video file, sound and so on


File stream

Files are operated in the form of streams in programs

Stream: the path of data between the data source (file) and the program (memory)

Input stream: the path of data from data source (file) to program (memory)

Output stream: the path of data from program (memory) to data source (file)



Common file operations

Constructors and methods for creating file objects

correlation method

new File(String pathname) //Build a File object based on the path
new File(File parent, String child) //Build according to parent directory file + child path
new File(String parent, String child) //Build according to parent directory + child path

createNewFile creates a new file

Application case demonstration:

Under disk f, create the file News1 txt,news2.txt,news3.txt, created in three different ways

package com.zzpedu.file;

import org.junit.jupiter.api.Test;

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

/**
 * Show me how to create a file
 */
public class FileCreate {

    //Method 1: new File (string pathname) / / build a File object according to the path
    @Test
    public void create01(){
        String filePath = "f:\\data\\news1.txt";
        File file = new File(filePath);
        try {
            file.createNewFile();
            System.out.println("File created successfully~");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //Method 2: new file (file parent, string child) / / build according to the parent directory file + child path
    //f:\\data\\news2.txt
    @Test
    public void create02(){
        String parent = "f:\\data\\";
        String child = "news2.txt";
        File parentFile = new File(parent);
        //The file object here, in a java program, is just an object
        File file = new File(parentFile,child);
        try {
            //Only when the createNewFile method is executed can the file be truly created on the disk
            file.createNewFile();
            System.out.println("File created successfully~");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //Method 3: new file (string parent, string child) / / build according to parent directory + child path
    @Test
    public void create03(){
        String parent = "f:\\data\\";
        String child = "news3.txt";
        File file = new File(parent,child);
        try {
            file.createNewFile();
            System.out.println("File created successfully~");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Execution effect:


Get information about the file

getName: returns the name of the file or directory represented by this abstract pathname.
getAbsolutePath: returns the absolute pathname string of this abstract pathname.
getParent: returns the parent of this abstract pathname, or the abstract pathname is null. If this pathname does not specify a parent directory.
Length: returns the length of the file represented by this abstract pathname.
Exists: tests whether the file or directory represented by this abstract pathname exists.
isFile: test whether the file represented by this abstract pathname is a normal file.
isDirectory: tests whether the file represented by this abstract pathname is a directory.

public class FileInformation {
    //Get file information
    @Test
    public void info(){
        //Create the file object first
        File file = new File("f:\\data\\news1.txt");
        //Call the corresponding method to get the corresponding information
        System.out.println("File name=" + file.getName());
        System.out.println("File absolute path=" + file.getAbsolutePath());
        System.out.println("The parent directory of the file=" + file.getParent());
        System.out.println("file size(byte)=" + file.length());//One letter has one byte and one Chinese has three bytes (utf-8 format)
        System.out.println("Does the file exist=" + file.exists());
        System.out.println("Is it a file=" + file.isFile());
        System.out.println("Is it a directory=" + file.isDirectory());
    }
}

Operation effect:

File name=news1.txt
 File absolute path=f:\data\news1.txt
 The parent directory of the file=f:\data
 file size(byte)=5
 Does the file exist=true
 Is it a file=true
 Is it a directory=false

Directory operation and file operation

mkdir: create a first level directory, such as: f:\data
mkdirs: create multi-level directories, such as: f:\data\demo\a\b\c
Delete: delete empty directories and files


Application case demonstration

1) Judge F: \ \ data \ \ News1 Txt exists. If it exists, delete it
2) Judge whether f:\data\demo02 exists and delete it if it exists. Otherwise, you will be prompted that it does not exist
3) Judge whether the f:\data\demo\a\b\c directory exists. If it exists, it will prompt that it already exists. Otherwise, it will be created

public class Directory_ {
    //Judge F: \ \ data \ \ News1 Txt exists. If it exists, delete it
    @Test
    public void m1(){
        String filePath = "f:\\data\\news1.txt";
        File file = new File(filePath);
        if(file.exists()){
            if(file.delete()){
                System.out.println("Delete succeeded");
            }else {
                System.out.println("Deletion failed");
            }
        }else {
            System.out.println("The file does not exist");
        }
    }
    //Judge whether f:\data\demo02 exists and delete it if it exists. Otherwise, you will be prompted that it does not exist
    //Here we need to show that in java programming, directories are also treated as files
    @Test
    public void m2(){
        String filePath = "f:\\data\\demo02";
        File file = new File(filePath);
        if(file.exists()){
            if(file.delete()){
                System.out.println("Delete succeeded");
            }else {
                System.out.println("Deletion failed");
            }
        }else {
            System.out.println("The directory does not exist~");
        }
    }
    //Judge whether the f:\data\demo\a\b\c directory exists. If it exists, it will prompt that it already exists. Otherwise, it will be created
    @Test
    public void m3(){
        String directoryPath = "f:\\data\\demo\\a\\b\\c";
        File file = new File(directoryPath);
        if(file.exists()){
            System.out.println(directoryPath + "Already exists~");
        }else {
            //Create a first level directory using mkdir(),
            //Create a multi-level directory using mkdirs()
            if(file.mkdirs()){
                System.out.println(directoryPath + " Created successfully...");
            }else {
                System.out.println(directoryPath + " Creation failed...");
            }
        }
    }
}



2, IO stream principle and stream classification

Java IO stream principle

1. I/O is the abbreviation of Input/Output. I/O technology is a very used technology because it handles data transmission. Such as reading / writing files, network communication, etc.

2. In Java programs, the input / output operation of data is carried out in the form of "stream".

3,java. Various "stream" class interfaces are provided under the IO package to obtain different kinds of data, and input and output data through methods

4. input: read external data (data from disk, optical disc and other storage devices) into the program (memory)

5. Output: output program (memory) data to disk, optical disc and other storage devices.


Parent classification of flow

According to different operation data units, it is divided into byte stream (8-bit) binary file and string (by character) text file

According to the flow direction of data flow, it is divided into input flow and output flow

According to different roles of flow, it can be divided into node flow, processing flow / packaging flow

abstract classByte streamCharacter stream
Input streamInputStreamReader
Output streamOutputStreamWriter

(1) Java's IO stream involves more than 40 classes, which are actually very regular and derived from the above four abstract base classes.
(2) The names of subclasses derived from these four classes are suffixed with their parent class names.


IO flow system diagram - common classes

1. IO flow system diagram



InputStream byte input stream

The InputStream abstract class is a superclass of all class byte input streams

Common subclasses of InputStream

1. FileInputStream: file input stream

2. BufferedInputStream: buffered byte input stream

3. ObjectInputStream: object byte input stream


InputStream system diagram:


Introduction to FileInputStream



FileInputStream application instance

Requirement: request to use FileInputStream to read hello Txt file and display the contents of the file to the console

First create the file and write the content.

/**
 * Demonstrate the use of FileInputStream (byte input stream file -- "program)
 */
public class FileInputStream_ {

    /**
     * Show me how to read files
     * The efficiency of reading a single byte is relatively low. If Chinese is read, it will be garbled (one Chinese (3 bytes utf-8), one will be read, one will be escaped, and one will be garbled)
     *  -> Use read(byte[] b)
     */
    @Test
    public void readFile01(){
        String filePath = "F:\\data\\hello.txt";
        int readData = 0;
        FileInputStream fileInputStream = null;
        try {
            //Create a FileInputStream object to read files
            fileInputStream = new FileInputStream(filePath);
            //Read one byte of data from the input stream. If no input is available, this method blocks.
            //If - 1 is returned, the reading is completed
            while ( (readData = fileInputStream.read()) != -1){
                System.out.print((char)readData);//Convert to char display
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //Close the file stream and free up resources
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Use read(byte[] b) to read files to improve efficiency
     */
    @Test
    public void readFile02(){
        String filePath = "F:\\data\\hello.txt";
        //Byte array
        byte[] buf = new byte[8];//Read 8 bytes at a time
        int readLen = 0;
        FileInputStream fileInputStream = null;
        try {
            //Create a FileInputStream object to read files
            fileInputStream = new FileInputStream(filePath);
            //Read up to b.length bytes of data from the input stream into the byte array. This method blocks until some input is available.
            //If - 1 is returned, the reading is completed
            //If the reading is normal, the number of bytes actually read is returned
            while ( (readLen = fileInputStream.read(buf)) != -1){
                System.out.print(new String(buf,0,readLen));//display
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //Close the file stream and free up resources
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Introduction to FileOutputStream

FileOutputStream application instance 1

Requirements: please use FileOutputStream to write "hello,world" in the a.txt file. If the file does not exist, the file will be created automatically (Note: the premise is that the directory already exists)

public class FileOutputStream01 {
    /**
     * Demonstrate that FileOutputStream writes data to a file,
     * If the file does not exist, it is created
     */
    @Test
    public void writerFile(){
        //Create FileOutputStream
        String filePath = "F:\\data\\a.txt";
        FileOutputStream fileOutputStream = null;

        try {
            //Get fileOutputStream object
            //explain:
            //1. If new FileOutputStream(filePath) is created, the original content will be overwritten when the content is written
            //2. new FileOutputStream(filePath, true) creation method: when writing content, it is appended to the file content
            fileOutputStream = new FileOutputStream(filePath,true);
            //Write a byte
            //fileOutputStream.write('Z');//char -> int
            //Write string
            String str = "zzp,world!";
            //str.getBytes() can convert a string into a byte array
            //fileOutputStream.write(str.getBytes());
            /*
                write(byte[] b, int off, int len)
                Writes len bytes to this file output stream from the specified byte array at offset off.
             */
            fileOutputStream.write(str.getBytes(),0, str.length()-1);


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

FileOutputStream application instance 2 copies files

Requirements: complete the copy of pictures / music by programming

public class FileCopy {
    public static void main(String[] args) {
        //When the file copy is completed, f:\data \ \ 45 Jpg copy to f:\data
        //Train of thought analysis:
        //1. Create the input stream of the file and read the file into the program
        //2. Create the output stream of the file, read the file data and write it to the specified file.
        String srcFilePath = "f:\\data\\45.jpg";
        String destFilePath = "e:\\data\\45.jpg";
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            //File input stream
            fileInputStream = new FileInputStream(srcFilePath);
            //File output stream
            fileOutputStream = new FileOutputStream(destFilePath);
            //Define a byte array
            byte[] buf = new byte[1024];
            int readLen = 0;
            while ((readLen = fileInputStream.read(buf)) != -1){
                //After reading, it is written to the file through fileOutputStream
                //That is, reading and writing
                fileOutputStream.write(buf,0,readLen);//Be sure to use the write of the specified length, because the length of the byte array is uncertain
            }
            System.out.println("Success copy ~");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //Close input and output streams
                if(fileInputStream != null){
                    fileInputStream.close();
                }
                if(fileOutputStream != null){
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

Introduction to FileReader and FileWriter

FileReader and FileWriter are character streams, that is, they operate according to characters

FileReader related methods

1)new FileReader(File/String)
2) Read: each time a single character is read, this character is returned. If the file is not ended, it returns - 1
3) read(char[] c): read multiple characters into the array in batch, and return the number of characters read. If the file is not finished, return - 1

Related API:

1) new String(char[] c): convert char [] to String
2) new String(char[], off, len): converts the specified part of char [] into a String


FileWriter common methods

1) new FileWriter(File/String): overwrite mode, which is equivalent to that the pointer of the stream is at the head end
2) new FileWriter(File/String, true): append mode, which is equivalent to the flow pointer at the end
3) writer(int): writes a single character
4) writer(chat []): writes the specified array
5) writer(char[], off, len): writes the specified part of the specified array
6) writer(string): writes the entire string
7) writer(string, off, len): writes the specified part of the string

Related API: String class: toCharArray: convert string to char []

be careful:
After the FileWriter is used, it must be closed or flushed, otherwise the specified file cannot be written!


FileReader and FileWriter application cases

requirement:
1) Using FileReader from story Txt read the content and display it

public class FileReader_ {

    /**
     * Single character read file
     */
    @Test
    public void readFile01(){
        String filePath = "F:\\data\\story.txt";
        int data = 0;
        //1. Create FileReader object
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(filePath);
            //Cyclic reading uses read() to read a single character
            while ((data = fileReader.read()) != -1){
                System.out.print((char)data);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fileReader != null){
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Character array read file
     */
    @Test
    public void readFile02(){
        String filePath = "F:\\data\\story.txt";
        int readLen = 0;
        char[] buf = new char[8];
        //1. Create FileReader object
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(filePath);
            //read(buf) is used for cyclic reading, and the number of characters actually read is returned
            //If - 1 is returned, it means the end of the file
            while ((readLen = fileReader.read(buf)) != -1){
                System.out.print(new String(buf,0,readLen));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fileReader != null){
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

2) Use FileWriter to write "after the wind and rain, see the rainbow" to note Txt file

public class FileWriter_ {
    public static void main(String[] args) {
        String filePath = "F:\\data\\note.txt";
        //Create FileWriter object
        FileWriter fileWriter = null;
        char[] chars = {'a','b','c'};
        try {
            fileWriter = new FileWriter(filePath);//The default is overwrite write
            //3) writer(int): writes a single character
            fileWriter.write('Z');
            //4) writer(chat []): writes the specified array
            fileWriter.write(chars);
            //5) writer(char[], off, len): writes the specified part of the specified array
            fileWriter.write("zzp sir",0,4);
            //6) writer(string): writes the entire string
            fileWriter.write(" Hello, China~");
            fileWriter.write(" After the wind and rain, you will see the rainbow ");
            //7) writer(string, off, len): writes the specified part of the string
            fileWriter.write("Great Wall Palace Museum",0,2);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //Corresponding to FileWriter, you must close the stream or flush to write data to the file
            //reason:
            /*
                Look at the source code public class streamencoder extensions writer {}
                private void writeBytes() throws IOException {
                    this.bb.flip();
                    int var1 = this.bb.limit();
                    int var2 = this.bb.position();

                    assert var2 <= var1;

                    int var3 = var2 <= var1 ? var1 - var2 : 0;
                    if (var3 > 0) {
                        if (this.ch != null) {
                            assert this.ch.write(this.bb) == var3 : var3;
                        } else {
                            this.out.write(this.bb.array(), this.bb.arrayOffset() + var2, var3);
                        }
                    }

                    this.bb.clear();
                }
             */
            if(fileWriter != null){
                try {
                    //fileWriter.flush();
                    //Close the file stream, which is equivalent to flush + close
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("Program end~");
    }
}



3, Node flow and processing flow

Basic introduction

1. Node streams can read and write data from a specific data source, such as FileReader and FileWriter

2. Processing flow (also known as wrapper flow) is "connected" to the existing flow (node flow or processing flow), which provides more powerful reading and writing functions and more flexibility for programs, such as BufferedReader and BufferedWriter


Node flow and processing flow diagram

classificationByte input streamByte output streamCharacter input streamCharacter output stream
abstract classInputStreamOutpurStreamReaderWriter
access filesFileInputStreamFileOutputStreamFileReaderFileWriterNode flow
Access arrayByteArrayInputStreamByteArrayOutputStreamCharArrayReaderCharArrayWriterNode flow
Access pipelinePipedInputStreamPipedOutputStreamPipedReaderPipedWriterNode flow
Access stringStringReaderStringWriterNode flow
Buffer streamBufferedInputStreamBufferedOutputStreamBufferedReaderBufferedWriterProcessing flow
Conversion flowInputStreamReaderOutputStreamWriterProcessing flow
Object flowObjectInputStreamObjectOutputStreamProcessing flow
Abstract base classFileInputStreamFileOutputStreamFilterReaderFilterWriterProcessing flow
Print streamPrintStreamPrintWriterProcessing flow
Push back input streamPushbackInputStreamPushbackReaderProcessing flow
Special flowDataInputStreamDataOutputStreamProcessing flow

give an example:


Differences and relations between node flow and processing flow

1. Node flow is the underlying flow / low-level flow, which is directly connected to the data source.

2. Processing flow (wrapping flow) wraps node flow, which can not only eliminate the implementation differences of different node flows, but also provide a more convenient method to complete input and output

3. The processing flow (also known as packing flow) wraps the node flow, using the decorator design pattern, and will not be directly connected to the data source [decorator design pattern]

The functions of processing flow are mainly reflected in the following two aspects:

1. Performance improvement: mainly increase the buffer to improve the efficiency of input and output

2. Convenient operation: the processing flow may provide a series of convenient methods to input and output large quantities of data at one time, which is more flexible and convenient to use


Simulate a simple modifier design pattern code demonstration

/**
 * Analog modifier design pattern
 */
public abstract class Reader_ {//abstract class
//    public void readFile(){}
//    public void readString(){}
    //In Reader_ Abstract classes, which are managed uniformly using the read method
    //When calling later, use the object dynamic binding mechanism to bind to the corresponding implementation subclass.
    public abstract void read();
}
/**
 * File node flow
 */
public class FileReader_ extends Reader_{
//    Public void readfile() {system. Out. Println ("read file...);}
    @Override
    public void read() {
        System.out.println("Read file...");
    }
}
/**
 * String node stream
 */
public class StringReader_ extends Reader_{
//    Public void readstring() {system. Out. Println ("read string...);}
    @Override
    public void read() {
        System.out.println("Read string...");
    }
}
/**
 * Make processing flow / packaging flow
 */
public class BufferedReader_ extends Reader_{
    private Reader_ reader_;//The property is Reader_ type
    //Receive Reader_ Subclass object
    public BufferedReader_(Reader_ reader_) {
        this.reader_ = reader_;
    }
    public void readFile(){//Encapsulate one layer
        //reader_.readFile();
        reader_.read();
    }
    //Make the method more flexible, read the file multiple times, or add cache byte[] char []
    public void readFiles(int num){
        for(int i = 0; i < num; i++){
            //reader_.readFile();
            reader_.read();
        }
    }
    //Extend readerString to batch process string data
    public void readStrings(int num){
        for(int i = 0; i < num; i++){
            //reader_.readString();
            reader_.read();
        }
    }

    @Override
    public void read() {
        reader_.read();
    }
}

Test:

public class Test_ {
    public static void main(String[] args) {
        //FileReader_
        BufferedReader_ bufferedReader_ = new BufferedReader_(new FileReader_());
        bufferedReader_.readFiles(3);
        //StringReader_
        BufferedReader_ bufferedReader_2 = new BufferedReader_(new StringReader_());
        bufferedReader_2.readStrings(2);
    }
}

Operation effect:

Read file...
Read file...
Read file...
Read string...
Read string...

Processing stream - BufferedReader and BufferedWriter

BufferedReader and BufferedWriter belong to character stream and read data according to characters

When closing the processing flow, you only need to close the outer flow



Application case

1. Use BufferedReader to read the text file and display it in the console

/**
 * Demonstrate the use of BufferedReader
 */
public class BufferedReader_ {
    public static void main(String[] args) throws IOException {
        String filePath = "F:\\data\\story.txt";
        //Create BufferedReader object
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
        //read
        String line;//Read by line, high efficiency
        //explain:
        //1. bufferedReader.readLine();  Yes, read files by line
        //2. When null is returned, it indicates that the file has been read
        while ((line = bufferedReader.readLine()) != null){
            System.out.println(line);
        }
        //Close the flow. Note here that you only need to close the bufferedReader, because the bottom layer will automatically close the node flow FileReader
        /*
        public void close() throws IOException {
            synchronized (lock) {
                if (in == null)
                    return;
                try {
                    in.close();//in.close() The new FileReader(filePath) we passed in is closed
                } finally {
                    in = null;
                    cb = null;
                }
            }
        }
         */
        bufferedReader.close();
    }
}

2. Use BufferedWriter to write "Mr. hello zzp" to the file

public class BufferedWriter_ {
    public static void main(String[] args) throws IOException {
        String filePath = "F:\\data\\ok.txt";
        //Create BufferedWriter object
        //explain:
        //1. new FileWriter(filePath,true) indicates write in append mode
        //2. new FileWriter(filePath) indicates overwrite mode writing
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
        bufferedWriter.write("hello,zzp sir!");
        bufferedWriter.newLine(); //Inserts a system related line break
        bufferedWriter.write("hello2,zzp sir!");
        bufferedWriter.newLine();
        bufferedWriter.write("hello3,zzp sir!");
        bufferedWriter.newLine();

        //Note: Just close the outer stream. The bottom layer will automatically close the incoming new FileWriter(filePath)
        bufferedWriter.close();
    }
}

3. Use BufferedReader and BufferedWriter to copy text files. Pay attention to file coding

/**
 * Text file copy
 */
public class BufferedCopy_ {
    public static void main(String[] args) {
        //explain:
        //1. BufferedReader and BufferedWriter operate according to characters
        //2. Do not operate binary files [sound, video, doc, pdf, etc.], which may cause file damage

        String scrFilePath = "F:\\data\\story.txt";
        String desFilePath = "F:\\data\\story2.txt";
        BufferedReader br = null;
        BufferedWriter bw = null;
        String line;
        try {
            br = new BufferedReader(new FileReader(scrFilePath));
            bw = new BufferedWriter(new FileWriter(desFilePath));
            //read file
            //Description: br Readline() reads the contents of a line without a newline
            while ((line = br.readLine()) != null){
                //Write without reading a line
                bw.write(line);
                //Insert a line break
                bw.newLine();
            }
            System.out.println("Copy complete~~~");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //Close flow
                if(br != null){
                    br.close();
                }
                if(bw != null){
                    bw.close();
                }
            }catch (IOException e){

            }
        }
    }
}

Processing streams - BufferedInputStream and BufferedOutputStream

Introduce BufferedInputStream

BufferedInputStream is a byte stream. When creating BufferedInputStream, an internal buffer array will be created


Introduce BufferedOutputStream

BufferedOutputStream is a byte stream that implements buffered output stream. Multiple bytes can be written to the underlying output stream instead of calling the underlying system every time bytes are written


Application case

Requirements: complete the copy of pictures / music by programming (BufferedIn... Stream is required)

/**
 * Demonstrate using BufferedInputStream and BufferedOutputStream
 * Using them, you can copy binary files and manipulate text files and binary files
 */
public class BufferedCopy02 {
    public static void main(String[] args) {
        String scrFilePath = "F:\\data\\Spill.mp3";
        String destFilePath = "F:\\data\\Spill02.mp3";
        //Create BufferedInputStream object
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //Because FileInputStream inherits InputStream
            bis = new BufferedInputStream(new FileInputStream(scrFilePath));
            bos = new BufferedOutputStream(new FileOutputStream(destFilePath));

            //Loop to read the file and write the file to destFilePath
            byte[] buf = new byte[1024];
            int readLine = 0;
            //When - 1 is returned, it indicates that the file has been read
            while ((readLine = bis.read(buf)) != -1){
                bos.write(buf,0,readLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //Close the flow, close the processing flow of the outer layer, and the bottom layer will close the node flow
                if (bis != null){
                    bis.close();
                }
                if (bos != null){
                    bos.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

Object stream - objectinputstream and ObjectOutputStream

Look at a demand

1. Save the int data of int num = 100 to the file. Note that it is not 100, but int 100. In addition, int 100 can be recovered directly from the file

2. Save the dog object dog = new dog ("Xiaohuang", 3) to a file and restore it from the file

3. The above requirement is to be able to serialize and deserialize basic data types or objects


Serialization and deserialization

1. Serialization is to save the value and data type of data when saving data

2. Deserialization is to recover the value and data type of data when recovering data

3. If an object needs to support serialization mechanism, its class must be serializable. In order to make a class serializable, the class must implement one of the following two interfaces:

Serializable / / this is a tag interface without methods
Externalizable / / the interface has methods that need to be implemented, so we generally use the Serializable interface


Basic introduction

ObjectInputStream

ObjectOutputStream

1. Function: provides methods for serializing and deserializing basic types or object types

2. ObjectOutputStream provides serialization

3. ObjectInputStream provides deserialization


Application case

1. Use ObjectOutputStream to serialize the basic data type and a Dog object (name,age) and save it to data Dat file

package com.zzpedu.outputstream_;

import java.io.*;

/**
 * Demonstrate the use of ObjectOutputStream to complete data serialization
 */
public class ObjectOutputStream_ {
    public static void main(String[] args) throws IOException {
        //After serialization, the saved file format is not a pure file, but according to its format
        String filePath = "f:\\data\\data.dat";

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));

        //Serialize data to filePath
        oos.writeInt(100);//Int - > integer (implement Serializable interface)
        oos.writeBoolean(true);//Boolean - > Boolean (implement Serializable interface)
        oos.writeChar('a');//Char - > character (implement Serializable interface)
        oos.writeDouble(9.5);//Double - > double (implement Serializable interface)
        oos.writeUTF("zzp sir");//String
        //Save a Dog object
        oos.writeObject(new Dog("Xiao Huang",3));

        oos.close();
        System.out.println("Data saved (serialized form)~~~~");
    }
}
package com.zzpedu.outputstream_;

import java.io.Serializable;

//If you need to serialize an object of a class, implement the Serializable interface
public class Dog implements Serializable {
    private String name;
    private int age;

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}

2. Use ObjectInputStream to read data DAT and deserialize the recovered data

package com.zzpedu.inputstream_;

import com.zzpedu.outputstream_.Dog;

import java.io.*;

/**
 * @author zzp
 */
public class ObjectInputStream_ {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //Specifies the file to deserialize
        String filePath = "f:\\data\\data.dat";
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
        //read
        //Interpretation:
        //1. The order of reading (deserialization) needs to be consistent with the order of the data you save (serialization)
        //2. Otherwise, an exception will occur
        System.out.println(ois.readInt());
        System.out.println(ois.readBoolean());
        System.out.println(ois.readChar());
        System.out.println(ois.readDouble());
        System.out.println(ois.readUTF());

        //The compilation type of Dog is Object, and the running type of Dog is Dog
        Object dog = ois.readObject();
        System.out.println("Operation type=" + dog.getClass());
        System.out.println("dog information=" + dog);//Underlying object - > dog

        //Here are particularly important details:
        //1. If we want to call Dog's method, we need to transform down
        //2. We need to define the Dog class as a package that can be referenced (the same package)
        Dog dog2 = (Dog)dog;
        System.out.println("dog.name=" + dog2.getName());

        //Close the stream, just close the outer stream, and the bottom stream will close the new FileInputStream(filePath) stream
        ois.close();
    }
}

Operation effect:

100
true
a
9.5
zzp sir
 Operation type=class com.zzpedu.outputstream_.Dog
dog information=Dog{name='Xiao Huang', age=3}
dog.name=Xiao Huang

Pay attention to implementation and details

1) Read and write in the same order

2) To serialize or deserialize an object, you need to implement the Serializable interface

3) serialVersionUID is recommended to be added to serialized classes to improve version compatibility

private static final long serialVersionUID = 1L;//serialVersionUID is the version number of serialization, which can improve compatibility

4) When serializing an object, all attributes are serialized by default, except for members decorated with static and transient [serialized file has no value, deserialized file is null]

5) When serializing an object, it is required that the type of the attribute inside also implement the serialization interface

6) Serialization is inheritable, that is, if a class has implemented serialization, all its subclasses have implemented serialization by default


Standard input / output stream

introduce

typeDefault device
System.in standard input streamInputStreamkeyboard
System.out standard output streamPrintStreammonitor
public class InputAndOutput {
    public static void main(String[] args) {
        //1. public final static InputStream in = null of system class;
        //2. System.in compilation type InputStream
        //3. System.in run type BufferedInputStream
        //4. System.in means that the standard input is the keyboard
        System.out.println(System.in.getClass());//class java.io.BufferedInputStream

        //Interpretation:
        //1. Public final static printstream out of system class = null;
        //2. System.out compilation type PrintStream
        //3. System.out run type PrintStream
        //4. System.out means that the standard output is the display
        System.out.println(System.out.getClass());//class java.io.PrintStream
    }
}

Application case 1

Traditional method system out. println(""); Use the out object to output data to the display

System.out.println("hello,world~");

Application case 2

The traditional method of Scanner is to receive data from the standard input keyboard

Scanner scanner = new Scanner(System.in);
System.out.println("input content");
System.out.println("next =" + scanner.next());


Transform stream - InputSreamReader and OutputStreamWriter

First look at a file scrambling problem, which leads to the necessity of learning transformation flow

Set the read file to a format other than utf-8

/**
 * Look at a Chinese garbled code problem
 */
public class CodeQuestion {
    public static void main(String[] args) throws IOException {
        //Read file to program
        //Idea:
        //1. Create character input stream BufferedReader [processing stream]
        //2. Use BufferedReader to read the file
        //3. By default, the read file is encoded according to utf-8
        String filePath = "F:\\data\\a.txt";
        BufferedReader br = new BufferedReader(new FileReader(filePath));
        String s = br.readLine();
        System.out.println("Read content:" + s);

        br.close();
    }
}

Execution effect:


introduce

1. Inputstreamreader: subclass of reader, which can wrap (convert) InputStream (byte stream) into reader (character stream)

2. Outputstreamwriter: subclass of Writer, which implements wrapping OutputStream (byte stream) into Writer (character stream)

3. When processing plain text data, if using character stream is more efficient and can effectively solve the Chinese problem, it is recommended to convert byte stream into character stream

4. You can specify the encoding format (such as utf-8, gbk, gb2312, IOS8859-1, etc.) when using


Application case

1. Program to package (convert) the byte stream FileInputStream into character stream InputStreamReader, read the file (according to utf-8/gbk format), and then package it into BufferedReader

/**
 * Demonstrates how to use InputStreamReader to transform streams to solve the problem of Chinese garbled code
 * Convert byte stream FileInputStream to character stream InputStreamReader, and specify the encoding utf-8
 */
public class InputStreamReader_ {
    public static void main(String[] args) throws IOException {
        String filePath = "F:\\data\\a.txt";
        //Interpretation:
        //1. Convert new FileInputStream(filePath) to new InputStreamReader
        //2. Specify the code gbk
        //InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");
        //3. Transfer InputStreamReader to BufferedReader
        //BufferedReader br = new BufferedReader(isr);

        //Write 2 and 3 together
        BufferedReader br = new BufferedReader(new InputStreamReader(
                                                    new FileInputStream(filePath), "gbk"));

        //4. Read
        String s = br.readLine();
        System.out.println("Read content=" + s);
        //5. Turn off the outer flow
        br.close();
    }
}

Operation effect:


2. Programmatically package (convert) the byte stream FileOutputStream into a character stream outputsramwriter to write to the file (according to gbk format, other can be specified, such as utf-8)

/**
 * Demonstrate the use of OutputStreamWriter
 * Convert FileOutputStream byte stream into character stream OutputStreamWriter
 * Specifies the encoding of the processing stream gbk/utf-8/utf8
 */
public class OutputStreamWriter_ {
    public static void main(String[] args) throws IOException {
        String filePath = "F:\\data\\zzp.txt";
        String chatSet = "gbk";
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath),chatSet);
        osw.write("hi,zzp sir");
        osw.close();
        System.out.println("according to " + chatSet + " File saved successfully~");
    }
}

Operation effect:


Print stream - PrintStream and PrintWriter

Print stream has only output stream and no input stream


Application instance PrintStream

/**
 * Demonstrate PrintStream (byte print stream / output stream)
 */
public class PrintStream_ {
    public static void main(String[] args) throws IOException {

        PrintStream out = System.out;
        //By default, the location of PrintStream output data is standard output, that is, the display
        /*
            public void print(String s) {
                if (s == null) {
                    s = "null";
                }
                write(s);
            }
         */
        out.print("john,hello");
        //Because the bottom layer of print uses the write method, we directly call write to print / output
        out.write("Hello, China".getBytes());
        out.close();

        //We can modify the location / device of print stream output
        //1. Modify the output to "f:\data\f1.txt"
        //2. "hello, world China ~" will be output to F: \ \ data \ \ F1 Txt file
        //3. Underlying source code
        /*
            private static native void setOut0(PrintStream out);

            public static void setOut(PrintStream out) {
                checkIO();
                setOut0(out); //native Method modifies out
            }
         */
        System.setOut(new PrintStream("f:\\data\\f1.txt"));
        System.out.println("hello,World China~");
    }
}

Operation effect:



Application instance PrintWriter

/**
 * Show me how to use PrintWriter
 */
public class PrintWriter_ {
    public static void main(String[] args) throws FileNotFoundException {
        //PrintWriter printWriter = new PrintWriter(System.out);// Output to console
        PrintWriter printWriter = new PrintWriter("f:\\data\\f2.txt");//output to a file
        printWriter.write("hi,Hello China~");
        printWriter.close();//The close here is to write data to the file and flush + close the stream
    }
}



4, Properties class

Look at a demand

The following configuration file is mysql properties

ip=192.168.0.13
user=root
pwd=123456

What are the programmed values of ip, user and pwd

analysis:

  1. traditional method
  2. Using the Properties class is easy to implement

Traditional method: first create MySQL under the src directory of the project Properties file

public class Properties01 {
    public static void main(String[] args) throws IOException {
        //Read mysql Properties file and get the values of IP, user and PWD

        BufferedReader br = new BufferedReader(new FileReader("src\\mysql.properties"));
        String line = "";
        while ((line = br.readLine()) != null){ //Cyclic reading
            String[] split = line.split("=");
            //If we ask to specify the value of ip
//            if("ip".equals(split[0])){
//                System.out.println(split[0] + "value is:" + split[1]);
//            }
            System.out.println(split[0] + "The values are:" + split[1]);
        }
        br.close();
    }
}

Operation effect:

ip The value is: 192.168.0.13
user The values are: root
pwd The value is 123456

Basic introduction

1) Collection class dedicated to reading configuration files

Configuration file format:
key=value
 key=value
....

2) Note: key value pairs do not need spaces, and values do not need to be enclosed in quotation marks. The default type is String

3) Common methods for Properties

  • Load: load the key value pair of the configuration file to the Properties object
  • list: displays data to the specified device / stream object
  • getProperty(key): get the value according to the key
  • setProperty(key,value): sets the key value pair to the Properties object
  • Store: store the key value pairs in Properties into the configuration file. In idea, save the information into the configuration file. If the meaning is Chinese, it will be stored as unicode code

http://tool.chinaz.com/tools/unicode.aspx unicode code query tool


Application case

1. Use the Properties class to complete the mysql Reading of Properties

public class Properties02 {
    public static void main(String[] args) throws IOException {
        //Use the properties class to read mysql Properties file
        //1. Create Properties object
        Properties properties = new Properties();
        //2. Load the specified configuration file
        properties.load(new FileReader("src\\mysql.properties"));
        //3. Display the k-v to the console
        properties.list(System.out);
        //4. Obtain the corresponding value according to the key
        String user = properties.getProperty("user");
        String pwd = properties.getProperty("pwd");
        System.out.println("user name=" + user);
        System.out.println("password=" + pwd);
    }
}

Operation effect:

-- listing properties --
user=root
pwd=123456
ip=192.168.0.13
 user name=root
 password=123456

2. Use the properties class to add key Val to the new file mysql2 Properties

3. Use the Properties class to complete the mysql2 Read Properties and modify a key val

public class Properties03 {
    public static void main(String[] args) throws IOException {
        //Use the Properties class to create a configuration file and modify the content of the configuration file
        Properties properties = new Properties();
        //create a file
        //1. If the file does not have a key, it is created
        //2. If the file has a key, it is modified
        /*
            Properties The parent class is Hashtable, and the bottom layer is the core method of Hashtable
            public synchronized V put(K key, V value) {
                // Make sure the value is not null
                if (value == null) {
                    throw new NullPointerException();
                }

                // Makes sure the key is not already in the hashtable.
                Entry<?,?> tab[] = table;
                int hash = key.hashCode();
                int index = (hash & 0x7FFFFFFF) % tab.length;
                @SuppressWarnings("unchecked")
                Entry<K,V> entry = (Entry<K,V>)tab[index];
                for(; entry != null ; entry = entry.next) {
                    if ((entry.hash == hash) && entry.key.equals(key)) {
                        V old = entry.value;
                        entry.value = value;//If the key exists, replace it
                        return old;
                    }
                }

                addEntry(hash, key, value, index);//If it is a new key, add it with addEntry
                return null;
            }

         */
        properties.setProperty("charset","utf8");
        properties.setProperty("user","Tom");//Note that when saving, Chinese is the unicode code value
        properties.setProperty("pwd","11111");
        //Store the k-v in a file
        //Comments parameter = > Hello world indicates the comments on the first line of the file
        properties.store(new FileWriter("src\\mysql2.properties"),"hello world");
        System.out.println("Successfully saved the configuration file~");
    }
}



task

1. Programming problem

(1) Judge whether there is a folder mytemp under disk f. if not, create mytemp
(2) In the f:\data\mytemp directory, create the file hello.txt
(3) If hello.txt already exists, you will be prompted that the file already exists. Do not create it again
(4) And in the hello.txt file, write hello,world China~

public class Homework01 {
    public static void main(String[] args) throws IOException {
        /*
        (1)Judge whether there is a folder mytemp under disk f. if not, create mytemp
        (2)In the 'f\data\mytemp' directory, create the file hello txt
        (3)If hello Txt already exists, indicating that the file already exists. Do not create it again
        (4)And in hello Txt file, write hello,world, China~
         */
        String directoryPath = "f:\\data\\mytemp";
        File file = new File(directoryPath);
        if(!file.exists()){
            //Create directory
            if(file.mkdir()){
                System.out.println("Create directory " + directoryPath + " success~");
            }else {
                System.out.println("Create directory " + directoryPath + " fail~");
            }
        }

        String filePath = directoryPath + "\\hello.txt";
        file = new File(filePath);
        if(!file.exists()){
            //create a file
            if(file.createNewFile()){
                System.out.println("create a file " + filePath + " success~");
                //If the file exists, we use the BufferedWriter character input stream to write the content
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
                bufferedWriter.write("hello,world China~");
                bufferedWriter.close();
            }else {
                System.out.println("create a file " + filePath + " fail~");
            }
        }else {
            //If the file already exists, a prompt message will be given
            System.out.println(filePath + " It already exists. Do not create it again...");
        }
    }
}

Operation effect:

Create directory f:\data\mytemp success~
create a file f:\data\mytemp\hello.txt success~


2. Programming problem

Requirements: use BufferedReader to read a text file, add line number to each line, and then output it to the screen together with the content.

public class Homework02 {
    public static void main(String[] args) {
        /*
        Requirements: use BufferedReader to read a text file, add line number to each line, and then output it to the screen together with the content.
         */
        String filePath = "f:\\data\\a.txt";
        BufferedReader br = null;
        String line = "";
        int lineNum = 0;
        try {
//            br = new BufferedReader(new FileReader(filePath));// Chinese may be garbled
            br = new BufferedReader(new InputStreamReader(
                    new FileInputStream(filePath), "gbk"));//Use InputStreamReader to specify the encoding format
            while ((line = br.readLine()) != null){
                System.out.println(++lineNum + "." + line);
            }

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(br != null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Operation effect:


3. Programming problem

(1) It is required to write a dog.properties
name=tom
age=5
color=red
(2) Write a dog class (name,age,color) to create a dog object and read the dog Properties complete the property initialization with the corresponding content and output
(3) Serialize the created Dog object to the dog.dat file

public class Homework03 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        /**
         * (1)It is required to write a dog Properties content name=tom age=5 color=red
         * (2)Write a dog class (name,age,color) to create a dog object and read the dog Properties complete the property initialization with the corresponding content and output
         * (3)Serialize the created Dog object to the file Dog Dat file
         */
        String filePath = "src\\dog.properties";
        Properties properties = new Properties();
        properties.load(new FileReader(filePath));
        //properties.list(System.out);  Is the test output correct
        String name = properties.getProperty("name");
        int age = Integer.parseInt(properties.getProperty("age"));
        String color = properties.getProperty("color");
        Dog dog = new Dog(name, age, color);
        System.out.println("======dog Object information=======");
        System.out.println(dog );

        //Serialize the created Dog object to the file Dog Dat file
        String serFilePath = "f:\\data\\dog.dat";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(serFilePath));
        oos.writeObject(dog);
        //Close flow
        oos.close();
        System.out.println("dog Object, serialization complete...");

        System.out.println("======read dog Object deserialization file=====");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(serFilePath));
        Dog dog1 = (Dog)ois.readObject();
        System.out.println("obtain dog object=" + dog1);
        //Close flow
        ois.close();
    }
}
class Dog implements Serializable {
    private String name;
    private int age;
    private String color;

    public Dog(String name, int age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }
}

Operation effect:

======dog Object information=======
Dog{name='tom', age=5, color='red'}
dog Object, serialization complete...
======read dog Object deserialization file=====
obtain dog object=Dog{name='tom', age=5, color='red'}

Keywords: Java Back-end

Added by LearningKid on Tue, 21 Dec 2021 14:13:30 +0200