In-depth IO want to learn must see! Benefit a lot~

I: Overview of IO Flow

IO streams are simply Input and Output streams. IO streams are mainly used to process data transmission between devices. Java operates on data through streams, while Java objects used for operation streams are in IO packages.
Classification:
According to operation data, it can be divided into byte stream and character stream. For example: Reader and InputStream
Divided by flow direction: input stream and output stream. For example: InputStream and OutputStream
The base class of byte streams:
    InputStream  ,   OutputStream
The abstract base class of character stream:
    Reader , Writer
Base classes of buffer streams:
Buffer Reader, Buffer Writer (Must Depend on Reader and Writer)
Base classes of binary streams:
Data InputStream, Data OutputStream (must depend on InputStream and OutputStream)
Serialization:
Object InputStream, Object OutputStream (must depend on InputStream and OutputStream)

Our program needs to read data from the data source through InputStream or Reader, and then write data to the target media using OutputStream or Writer. InputStream and Reader are associated with data sources, OutputStream and writer are associated with target media. The following figure illustrates this point:

2: Character Stream

1. Character Stream Profile:
01. Objects in the character stream are fused with the encoding table, which is the default encoding table of the system. Our systems are generally GBK coded.
02. Character streams are only used to process text data, while byte streams are used to process media data.
03. The most common representation of data is files. The subclasses of character streams used to manipulate files are FileReader and FileWriter.
2. Character stream read-write:
Notes:
flush() must be refreshed after writing to the file
02. Remember to close the stream when you run out of it
03. Use flow objects to throw IO exceptions
04. When defining file paths, you can use "/" or "\"
05. When creating a file, if there is a file with the same name in the directory, it will be overwritten.
06. When reading a file, it must be guaranteed that the file already exists, otherwise an exception will occur.
 
Example:
 
public class CharDemo {
    public static void main( String[] args )
    {
        //Create input and output streams
        Reader reader = null;
        Writer writer = null;
        try {
            //The purpose is to identify the destination of the data to be stored.  
            reader = new FileReader("e:/a.txt");
            writer = new FileWriter("e:/a.txt",true);
            //Write in a file
            writer.write("La La La");
            writer.write("La La La");
            writer.write("I'm a newspaper salesman.");
            //flush
            writer.flush();
            writer.write("La La La");
            writer.write("La La La");
            writer.write("La La La");
            writer.close();
            //read
            //Create how many characters to read at a time
            char[] data = new char[1024];
            int num = 0;
            StringBuffer sb = new StringBuffer();
            //Judge that if there is data in the file, add data later
            while ((num = reader.read(data))!=-1){
                sb.append(data);
            }
            System.out.println(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // writer.close();It should be placed after adding data.
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

3: Byte stream

In Java, byte streams are generally suitable for processing byte data (such as pictures and videos) and character streams are suitable for processing character data (such as text files), but there is no strict functional division between them, because the existence of conversion streams makes data processing more flexible. InputStream and OutputStream are the base classes of byte input stream and byte output stream respectively. Their subclasses are byte stream, which is mainly used to process binary data by byte.  

Don't talk too much nonsense, the example above!

public class ByteDemo {
    public static void main( String[] args )
    {
        //Create input and output stream objects
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream("e:/a.txt");
            //true Represents whether to splice into a file without deleting previous content
            outputStream = new FileOutputStream("e:/a.txt",true);
            //Write to the file first
            outputStream.write("54321".getBytes());//outputStream.flush();I didn't realize it.
            //read Method returns 0-255 If the number between the streams reads to the end, it returns-1
            int num = 0;
            while ((num=inputStream.read())!=1){
                System.out.println((char) num);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

IV: Binary Stream

There are two top-level classes for binary streams: InputStream and OutputStream. The following two classes are various subsidiary classes. By contrast, the relationship between binary streams is more diverse and complex than that of character streams. With regard to binary streams, LineNumberInputStream and StringBufferInputStream classes are not used in JDK 1.5 as far as possible because they have been discarded.

 

Let's show you a simple example to learn about it.
 
 
public class DataDemo {
    public static void main(String[] args) {
        //Create input and output stream objects
        InputStream inputStream = null;
        OutputStream outputStream=null;
        DataInputStream dis = null;
        DataOutputStream dos=null;
        try {
            //Get the input stream   txt Into memory
            inputStream=new FileInputStream("e:/a.txt");
            dis=new DataInputStream(inputStream);
            //Get the output stream
            outputStream=new FileOutputStream("e:/public/a.txt");
            dos=new DataOutputStream(outputStream);
            //Read first
            int num=0;
            while ((num=dis.read())!=-1){
                dos.write(num);  //copy
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {  //Release resources
            try {
                dos.close();
                dis.close();
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Fifth: Buffer Stream

Definition: Create a buffer of appropriate size between memory and hard disk. When memory and hard disk access data, it can increase the number of times to access hard disk and improve efficiency.

Classification: Buffered Input Stream and Buffered Output Stream and Buffered Reader and Buffered Write.

A small case, a great understanding~

public class BufferDemo {
    public static void main(String[] args) {
        //Create an output stream
        Reader reader = null;
        Writer writer = null;
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            writer = new FileWriter("e:/a.txt",true);
            bw = new BufferedWriter(writer);
            bw.write("Hello!");
//Line feed bw.newLine(); bw.write(
"llll");
//flush bw.flush(); bw.write(
"222"); bw.write("333"); bw.write("444"); bw.close(); writer.close(); //If you don't close the next two sentences, you can't get them. //read reader=new FileReader("e:/a.txt"); br=new BufferedReader(reader);//encapsulation String line=null; StringBuffer sb=new StringBuffer(); while ((line=br.readLine())!=null){ sb.append(line); } System.out.println(sb.toString()); } catch (IOException e) { e.printStackTrace(); }finally { try { br.close(); reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }

Sixth: serialization and deserialization

Serialization: The process of converting an object into a sequence of bytes is called object serialization. (Continuation)
Deserialization: The process of restoring byte sequences to objects is called object deserialization.

For example, login registration, registration is serialization, login is deserialization!!! Why? Registration is to store the user's information on the hard disk, that is, persistence! Login is to return the information, which means to read from the hard disk and call it deserialization! ______________

A chestnut is more intuitive!

Let's start with an entity class.

package com.ftx;

import java.io.Serializable;

/**
 * @author A cat that is tied up
 * @create 2018-07-03 15:49
 * @Blog address:https://home.cnblogs.com/u/fl72/
 * Serializable interface must be implemented, otherwise in the process of execution, errors will be reported! No serialization
 **/

public class User implements Serializable {
    private String userName;
    private String userPassword;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }
    public User(String userName, String userPassword) {
        this.userName = userName;
        this.userPassword = userPassword;
    }

    public User() {
    }

    @Override
    public String toString() {
        return "User{" +
                "userName='" + userName + '\'' +
                ", userPassword='" + userPassword + '\'' +
                '}';
    }
}

Next, the good play is about to begin! _____________

public class ObjectDemo {
    static Scanner input = new Scanner(System.in);
    //Create required input and output stream objects
    static InputStream inputStream = null;
    static OutputStream outputStream = null;
    static ObjectInputStream objectInputStream = null;
    static ObjectOutputStream objectOutputStream = null;

    public static void main(String[] args) {
        //Registration serialization
        //register();
        //Login deserialization
        login();
    }

    //register
    private static void register() {
        User user = new User();
        System.out.println("Please enter your username:");
        user.setUserName(input.next());
        System.out.println("Please enter your password:");
        user.setUserPassword(input.next());

        try {
            outputStream = new FileOutputStream("e:/user.txt");
            objectOutputStream = new ObjectOutputStream(outputStream);
            //Export objects to files
            objectOutputStream.writeObject(user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                objectOutputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //Sign in
    private static void login() {
        try {
            inputStream = new FileInputStream("e:/user.txt");
            objectInputStream = new ObjectInputStream(inputStream);
            //read object
            User user = (User) objectInputStream.readObject();
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                objectInputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

So, you see?

Seven: Byte-to-byte character stream

public static void convertByteToChar() throws IOException{
     File file= new File( "d:/test.txt"); 
    //Get a byte stream InputStream is= new FileInputStream( file);
     //Converting a byte stream to a character stream is actually the result of combining a character stream with a byte stream.
     Reader reader= new InputStreamReader( is);
     char [] byteArray= new char[( int) file.length()]; 
    int size= reader.read( byteArray); 
    System. out.println( "Size:"+size +";content:" +new String(byteArray));
     is.close(); 
    reader.close();
 }

VIII: Use of File

  

public class FileDemo
{
    static Scanner input=new Scanner(System.in);
    public static void main( String[] args )
    {
        System.out.println( "*************Welcome to File Operating System*************" );
        System.out.println( "*************1.create a file*************" );
        System.out.println( "*************2.Delete files*************" );
        System.out.println( "*************3.Modify file*************" );
        System.out.println( "*************4.create folder*************" );
        System.out.println( "*************5.Query the list of all files under the folder*************" );
        System.out.println( "*************Please choose:*************" );

        //Get user input
        int choose = input.nextInt();
        switch (choose){
            case 1://create a file
                createNewFile();
                break;
            case 2://Delete files
                deleteFile();
                break;
            case 3://Modify file
                updateFile();
                break;
            case 4://create folder
                mkdirs();
                break;
            case 5://Query the list of all files under the folder
                findFileList();
                break;
        }
    }
    //Query the list of all files under the folder
    private static void findFileList() {
        System.out.println("Please enter the name of the folder you want to query: (default is E: /)");
        String fileName = input.next();
        //Establish File object
        File file=new File("E:/"+fileName);
        File[] files = file.listFiles();
        int driNums = 0;
        int fileNums = 0;
        System.out.println("This folder contains:");
        for (File f:files) {
            if (f.isDirectory()){
                driNums++;
                System.out.println(f.getName());
            }
            if (f.isFile()){
                fileNums++;
                System.out.println(f.getName());
            }
        }
        System.out.println("The folders under this folder are"+driNums);
        System.out.println("The files under this folder are"+fileNums);
    }

    //create folder
    private static void mkdirs() {
        System.out.println("Please enter the name of the created file: (default is E: /)");
        String fileName = input.next();
        //Establish File object
        File file=new File("E:/"+fileName);
        if(file.mkdirs()){
            System.out.println("Create success!");
        }else{
            System.out.println("Creation failed!");
        }
    }

    //Modify file
    private static void updateFile() {
        System.out.println("Please enter the name of the file you need to modify: (default is E: /)");
        String oldFileName = input.next();
        System.out.println("Please enter the name of the modified file: (default is E: /)");
        String newFileName = input.next();
        //Establish File object
        File oldFile=new File("E:/"+oldFileName);
        File newFile=new File("E:/"+newFileName);
        if (oldFile.renameTo(newFile)){
            System.out.println("Successful revision!");
        }else {
            System.out.println("Modification failed!");
        }
    }

    //Delete files
    private static void deleteFile() {
        System.out.println("Please enter the name of the file you want to delete: (default is E: /)");
        String fileName = input.next();
        //Establish File object
        File file=new File("E:/"+fileName);
        if(file.exists()){
            boolean falg = file.delete();
            if (falg){
                System.out.println("Delete successfully!");
            }else {
                System.out.println("Delete failed!");
            }
        }else {
            System.out.println("The file you entered does not exist!");
        }
    }

    //create a file
    private static void createNewFile() {
        System.out.println("Please enter the name of the file: (default is E: /)");
        String fileName = input.next();
        //Establish File object
        File file=new File("E:/"+fileName);
        if (file.exists()){  //file already exists
            System.out.println("This document already exists!");
        }else{
            try {
                boolean  flag= file.createNewFile();
                if (flag){
                    System.out.println("File Creation Successful!");
                }else{
                    System.out.println("File creation failed!");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 

 

 

 

Keywords: Java encoding JDK

Added by kontesto on Fri, 17 May 2019 19:47:45 +0300