Prepare for the job hopping interview , Today we begin to enter Java Basic review . I hope students with poor foundation will finish reading this article , Be able to master generics , And the students with good foundation should have the right to review , I hope that after reading this article, you can have a little green memory .

One 、 What is? IO flow ?

Imagine a scene : We edit files on the computer , It can be saved to the hard disk , It can also be copied to U Plate . So this seemingly simple process , Behind it is the transmission of data .

Data transmission , That's the flow of data . Since it is a flow, there will be a direction , There are in and out directions . For example, a chestnut that uploads files , Now there are three objects , file 、 Applications 、 The destination address of the upload ( The server ). There are two steps to simplify uploading files :

  • Applications read files ( This is the entry direction , The file is read into the application )
  • Applications write files ( This is the way out , Write to the destination address after reading )

Notice that the in and out are relative , It's relative to the application . If relative to the server , The upload file operation is the entry direction , Read in from the application .Java in I/O Operation mainly refers to the use of java.io Content under package , Input 、 Output operation . Input is also called reading data , Output is also called write data .

Two 、IO Classification of flows

I don't agree with a lot of... On the Internet IO Graph of flow , They just simply put io The stream is divided into byte stream and character stream . This classification is not bad , It's just too bloated 、 Hard to remember .

First of all, I summed it up by myself IO My mind map , I divide it into node flow and processing flow first , The node flow is in direct contact with the data source , The processing flow is based on the node flow for various purposes IO flow . And then according to the type of operation , Divide into 8 A small class , And then there are the bytes 、 Character classification , Finally, the input 、 Classification of output . See the mind map below ( It may not be clear , Reply in the background if necessary IO Flow to get the original mind map )

According to the flow of data, it can be divided into : Input and output streams .

  • Input stream : A stream that reads data from other devices into memory .
  • Output stream : Take data from memory Stream written to other devices .

According to the type of data, it can be divided into : Byte stream and character stream .

  • Byte stream : In bytes , Read and write data streams .
  • Character stream : In characters , Read and write data streams .

Java IO  flow

IO It will take several articles to make the flow clear , Today we're going to review the file stream .

2.1 Everything is good

All documents ( Including pictures 、 music 、 video ), It's all bytes . So byte stream can transfer any file data . At the time of operation flow , No matter what kind of flow object is used , The underlying transmission is always binary data .

2.2 What is file stream ?

A file stream is a stream that directly operates on files , File stream is divided into byte stream (FileInputStream and FileOutputStream) And character streams (FileReader and FileWriter). The byte stream can be used to operate all files , Character stream can only be used to manipulate text files .

3、 ... and 、 Use file byte stream

 Byte output stream

 Byte input stream

3.1 FileOutputStream

java.io.FileOutputStream Class inherited from OutputStream It's a file output stream , Used to write data to a file .

Construction method : It can be constructed with a file path , Can also be created File Object .

Write data examples :

/**
 * Project Name:review_java <br/>
 * Package Name:com.nasus.io.filestream <br/>
 * Date:2020/1/5 19:24 <br/>
 *
 * @author <a href="turodog@foxmail.com">chenzy</a><br/>
 */
public class FOSWriterStream {

    public static void main(String[] args) throws IOException {
        //  Create a stream object with a file name , In the constructor  true  It means to add a continuation at the end of the original data 
        FileOutputStream fos = new FileOutputStream("fos.txt", true);

        // 1、 Write... Byte by byte 
        fos.write(97); // 97  Of  ascll  Code is  a
        fos.write(98); // 98  Of  ascll  Code is  b
        fos.write(99); // 99  Of  ascll  Code is  c

        // 2、 Write a new line ,  The newline symbol is converted into an array to write 
        fos.write("\r\n".getBytes());

        //  String to byte array 
        byte[] b = " A good loser ".getBytes();
        // 3、 Write byte array data 
        fos.write(b);

        // 4、 Write the specified length byte array data ( Do not exceed  b  The length of , Otherwise, the array is out of bounds )
        fos.write(b, 0, b.length);

        //  close resource 
        fos.close();
    }

}

3.2 FileInputStream

java.io.FileInputStream Class inherited from InputStream It's a file input stream , Used to read data from a file .

Construction method : It can be constructed with a file path , Can also be created File Object .

Read data example :

/**
 * Project Name:review_java <br/>
 * Package Name:com.nasus.io.filestream <br/>
 * Date:2020/1/5 19:31 <br/>
 *
 * @author <a href="turodog@foxmail.com">chenzy</a><br/>
 */
public class FISReadStream {

    public static void main(String[] args) throws IOException {
        // 1、 Read bytes one by one 
        int b;
        FileInputStream fis1 = new FileInputStream("fis.txt");
        //  Cyclic reading 
        while ((b = fis1.read())!=-1) {
            System.out.println((char)b);
        }
        //  close resource 
        fis1.close();

        System.out.println("---- Beautiful dividing line ----");

        // 2、 Define byte array read 
        int length;
        FileInputStream fis2 = new FileInputStream("fis.txt");
        //  Define byte array , As a container for byte data 
        byte[] bytes = new byte[1024];
        //  Cyclic reading 
        while ((length = fis2.read(bytes))!=-1) {
            //  After each read , Turn an array into a string to print 
            System.out.println(new String(bytes, 0, length));
        }
        //  close resource 
        fis2.close();
    }

}

Copy file example :

/**
 * Project Name:review_java <br/>
 * Package Name:com.nasus.io.filestream <br/>
 * Date:2020/1/5 19:43 <br/>
 *
 * @author <a href="turodog@foxmail.com">chenzy</a><br/>
 */
public class FileCopyStream {

    public static void main(String[] args) throws IOException {

        //  specify data source 
        FileInputStream fis = new FileInputStream("Java IO  flow .png");
        //  Designated destination 
        FileOutputStream fos = new FileOutputStream(" flow .png");

        //  Define an array 
        byte[] b = new byte[1024];
        //  Define the length 
        int len;
        //  Cyclic reading 
        while ((len = fis.read(b))!=-1) {
            //  Writing data 
            fos.write(b, 0 , len);
        }

        //  close resource , Turn it on and off , Turn it on and off 
        fos.close();
        fis.close();
    }

}

3.3 Why is there garbled code when byte stream processes Chinese characters ?

First of all, make it clear : A letter takes up a byte , A Chinese character takes up two bytes , So when the byte stream reads the character stream, there will be garbled or incomplete display . So when using byte stream to operate a file containing Chinese characters , To prevent garbled code, you need to convert to character stream and specify encoding format .( this , Later, we will review )

Four 、 Using file character stream

When using a byte stream to read a text file , There may be a small problem . When you encounter Chinese characters , May not display full characters , That's because a Chinese character may take up more than one byte to store . therefore Java Provide some character stream classes , Read and write data in characters , It is specially used for processing text files .

 Character input stream

 Character output stream , Writing documents

4.1 FileReader

java.io.FileReader Class inherited from Reader class , Is a convenient class for reading character files . The system's default character encoding and default byte buffer are used during construction .

Construction method : It can be constructed with a file path , Can also be created File Object .

  • Character encoding : Rules for byte to character correspondence .Windows The default Chinese code of the system is GBK Encoding table
  • Byte buffer : An array of bytes , Used to temporarily store byte data .

PS: Sometimes there's garbled code , Think more about coding : The rules of byte and character don't match .

Read data example :

/**
 * Project Name:review_java <br/>
 * Package Name:com.nasus.io.filereadwrite <br/>
 * Date:2020/1/5 20:19 <br/>
 *
 * @author <a href="turodog@foxmail.com">chenzy</a><br/>
 */
public class FileRead {

    public static void main(String[] args) throws IOException {

        // 1、 Read character by character 
        int b = 0;
        FileReader fileReader1 = new FileReader("read.txt");
        //  Cyclic reading 
        while ((b = fileReader1.read())!=-1) {
            //  The automatic promotion type is promoted to  int  type , So use  char  Strong go 
            System.out.println((char)b);
        }
        //  Closed flow 
        fileReader1.close();

        System.out.println("---- Beautiful dividing line ----");

        // 2、 Using character arrays , Read two characters at a time 
        int length = 0;
        FileReader fileReader2 = new FileReader("read.txt");
        char[] charArray = new char[2];
        //  Reading data 
        while ((length = fileReader2.read(charArray)) != -1) {
            System.out.println(new String(charArray, 0, length));
        }
        //  Closed flow 
        fileReader2.close();
    }

}

4.2 FileWriter

java.io.FileWriter Class is a convenient class for writing characters to files . The system's default character encoding and default byte buffer are used during construction .

Construction method : It can be constructed with a file path , Can also be created File Object .

Write data examples :

public static void main(String[] args) throws IOException {
        //  Create a stream object with a file name ,true  It means to add a continuation at the end of the original data 
        FileWriter fileWriter = new FileWriter("fw.txt", true);

        // 1、 Write the characters one by one 
        fileWriter.write(97);
        fileWriter.write('C');
        fileWriter.write('Z');
        fileWriter.write('Y');
        //  You can write the data in the character array each time 30000 You can write the data in the character array each time .
        fileWriter.write(30000);


        // 2、 Write a string 
        fileWriter.write(" It's a ");

        // 3、 Write  Windows  Line break 
        fileWriter.write("\r\n");

        // 4、 Write an array of strings 
        //  String to byte array 
        char[] chars = " Good losers ".toCharArray();
        fileWriter.write(chars, 0, chars.length);

        //  close resource ,close Before method call , The data is just saved to the buffer , Not written in the file .
        fileWriter.close();
    }

Refresh and close :

Because of the built-in buffer , If you don't turn off the output stream , Unable to write characters to file . But closed stream objects , It's impossible to write data . If we want to write data , Want to continue to use the stream , Need flush The method .

  • flush : Refresh buffer , Stream objects can continue to use .
  • close : Refresh the buffer first , Then inform the system to release resources . Stream objects can no longer be used .
/**
 * Project Name:review_java <br/>
 * Package Name:com.nasus.io.filereadwrite <br/>
 * Date:2020/1/5 22:25 <br/>
 *
 * @author <a href="turodog@foxmail.com">chenzy</a><br/>
 */
public class FileFlushClose {

    public static void main(String[] args) throws IOException {
        //  Create a stream object with a file name 
        FileWriter fw = new FileWriter("fw.txt");
        // 1、 adopt  flush  Writing data 
        //  Write the number  1  Characters 
        fw.write(' brush ');
        fw.flush();

        //  Continue to write  2  Characters , Write success 
        fw.write(' new ');
        fw.flush();

        // 2、 adopt  close  Writing data , Not available after stream is closed 
        //  Write the number  1  Characters 
        fw.write(' Turn off ');
        fw.close();

        //  Continue to write  2  Characters ,【 Report errors 】java.io.IOException: Stream closed
        fw.write(' close ');
        fw.close();
    }
}

5、 ... and 、 Source code address

  • github Source code address :https://github.com/turoDog/review_java

If you see this , Like this article , Help " forward " Or order " Looking at ", Would you? ? I wish you all the best 2020 A rich man . WeChat search 「 A good loser 」, Welcome to your attention .

reply 「1024」 Send you a complete set java、python、c++、go、 front end 、linux、 Algorithm 、 big data 、 Artificial intelligence 、 Small program and English Course .

reply 「 e-book 」 Send you 50+ Ben java e-book .

 Most comprehensive tutorial