Learning IO flow in Java

catalogue

 1.File class

Basic functions of File class

2.IO flow

Classification of IO

Byte stream - output

Byte stream try catch finally catch exception

Byte stream - input

Buffer stream

Character stream - encoding table

Character stream - write out data

Character stream - read data

Buffer stream

Conversion flow

Object operation flow

Properties

Properties-load,store

 1.File class

When reading, tell the virtual machine where to operate (file / folder)
Operate on (file / folder) itself, including creation, deletion, etc.

FIle class overview and construction method
File: it is an abstract representation of file and directory paths
Files and directories can be encapsulated into objects through File
The object encapsulated by File is just a pathname. It may or may not exist.

Method name

Explain

                File(String pathname)Converts the File instance with the given pathname string
                File(String parent,String child)Create a new File instance from the parent and child pathname strings
                File(File parent,String child)Creates a new File instance from the parent pathname and child pathname strings

Basic functions of File class

Method name

Explain

                public boolean creatnNewFile ()Create a new empty file
                public boolean mkdir ()Create a stand-alone folder
                public boolean mkdirs ()Create a multi-level folder
                public boolean delete ()Delete the file or empty directory represented by this abstract path
                public boolean isDirectory ()Test whether the File represented by this abstract pathname is a directory
                public boolean isFile ()Test whether the File represented by this abstract pathname is a File
                public boolean exists ()Test whether the File represented by this abstract pathname exists
                public String getName ()Returns the name of the file or directory represented by this abstract pathname
                public String getAbsolutePath ()Returns the absolute pathname string for this abstract pathname
                public Long lastModified ()Returns the time when the file represented by this abstract pathname was last modified
                public File[] listFiles ()Returns an array of files representing directories and files in the path
public class Main {
    public static void main(String[] args) throws IOException {
        File f1 = new File("src/demo2/a.txt");
        File f2 = new File("src/demo2/b.txt");
        //create a file
        System.out.println(f1.createNewFile());
        System.out.println(f2.createNewFile());
    }
}

Execution results:

Summary:
If the path file exists, false is returned and the file is not created
If the path file does not exist, return true to create the file (only files can be created)

public class Main {
    public static void main(String[] args) throws IOException {
        File f1 = new File("src/demo2/aaa/bbb/ccc.txt");
        //Create multi-level directory
        System.out.println(f1.mkdirs());
    }
}

Execution results:

Summary:
If the path exists, false is returned and no folder is created
If the path does not exist, return true to create a folder (only folders can be created)

public class Main {
    public static void main(String[] args) throws IOException {
        File f1 = new File("src/demo2/aaa/bbb/ccc.txt/a.txt");
        //Delete files or directories
        System.out.println(f1.delete());
    }
}

Execution results:


Summary:
        1. Those that do not go to the recycle bin (cannot be easily restored after deletion)
        2. Only existing files and empty folders can be deleted

public class Main {
    public static void main(String[] args) throws IOException {
        File f1 = new File("src/demo2/aaa");
        File f2 = new File("src/demo2/aaa/a.txt");
        //Determine whether the File is a directory
        System.out.println(f1.isDirectory());
        //Judge whether File is a File
        System.out.println(f2.isFile());
        //Determine whether the File exists
        System.out.println(f2.exists());
        //Get File absolute path
        System.out.println(f1.getAbsolutePath());
        //Get file name or folder name
        System.out.println(f2.getName());
        //Get the last modification time
        Date date = new Date(f2.lastModified());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy year HH:mm:ss");
        String result = sdf.format(date);
        System.out.println(result);
    }
}

Execution results:

public class Main {
    public static void main(String[] args) throws IOException {
        File f = new File("C:/");
        //Returns all files and folders in the path
        for (File file : f.listFiles()) {
            System.out.println(file);
        }
    }
}

Execution results:

2.IO flow

Overview of IO (flow system, flow structure, flow operation steps)
I: in input
O: out output

IO data transmission can be regarded as a data flow direction. According to the flow direction, it is necessary to read and write with "memory" as the reference
Description:
Memory (Java program) - > hard disk (file): output (write data)
Hard disk (file) - > memory (Java program): input (read data)

Classification of IO

Byte stream - output

Steps:
        1. Create a byte stream object (if it does not exist, it will be created according to whether the construction parameters are cleared)
        2. Write data
        3. Release resources (pay attention to releasing resources after use)

Construction method:
        FileOutputStream(String name,boolean append)
Creates an output file stream that writes data to a file with the specified name

Classification of methods for writing data

Method name

Explain

    void write (int b)Writes the specified bytes to this file. The output stream writes one byte of data at a time
    void write (byte [] b) 

Writes b.length bytes from the specified byte array to this file output stream

Write one byte array data at a time

   void write (byte[] b, int off, int len)

Start len bytes from the specified byte array and offset off

Write the output stream of this file to write part of the data of one byte array at a time

public class Main {
    public static void main(String[] args) throws IOException {
        //If the directory does not exist, an error will be reported, and if the file does not exist, it will be created automatically
        File f = new File("src/a.txt");
        FileOutputStream fos = new FileOutputStream(f,true);
        int b1 = 95;
        byte[] b2 = {98,99,100};
        fos.write(b1);

        fos.write("\r\n".getBytes());
        fos.write("take off".getBytes());

        fos.write(b2);

        fos.write(System.lineSeparator().getBytes());

        fos.write(b2,0,2);
        fos.close();
    }
}

Execution results:
  

Byte stream try catch finally catch exception

Format:
        try{
Codes with possible exceptions;    
} catch (exception class name variable name){
Exception handling code;
        } finally {
Perform all clearing operations;
        }

finally features:
Statements that are finally controlled must be executed unless the JVM exits

public class Main {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
            //If the directory does not exist, an error will be reported, and if the file does not exist, it will be created automatically
            File f = new File("src/a.txt");
            fos = new FileOutputStream(f,true);
            byte[] b2 = {98,99,100};
            fos.write(b2);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Byte stream - input

Steps:
        1. Create byte input stream object (must exist)
        2. Read a byte
        3. Close flow

Construction method:
        FileInputStream(String name)

public class Main {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("D:/a.txt");
        FileOutputStream fos = new FileOutputStream("D:/b.txt");
        //Output char
        int read1;
        while ((read1 = fis.read()) != -1){
            System.out.print((char)read1);
        }
        //Output String
        byte[] b = new byte[1024];
        int read2;
        while ((read2 = fis.read(b)) != -1){
            System.out.print(new String(b));
        }
        //write file
        int read3;
        while ((read3 = fis.read()) != -1){
            fos.write(read3);
        }
        fis.close();
        fos.close();
    }
}

Execution results:

Buffer stream

Byte buffer stream
BufferedOutputStream: byte buffered output stream
BufferedInputStream: byte buffered input stream

Construction method (default buffer size: 8192 bytes)
Byte buffered output stream: BufferedOutputStream (OutputStream out)
Byte buffered input stream: BufferedInputStream (InputStream in)

Why does the construction method need a byte stream rather than a specific file or path?
Byte buffer stream only provides buffer, and the real reading and writing data still depends on the line operation of basic byte stream objects

public class Main {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("src/ASCII.jpg");
        BufferedInputStream bis = new BufferedInputStream(fis);
        FileOutputStream fos = new FileOutputStream("src/cpASCII2.jpg");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        byte[] b = new byte[1024];
        int len;
        while ((len = fis.read(b)) != -1){
            fos.write(b,0,len);
        }
        bis.close();
        bos.close();
    }
}

Execution results:


Byte stream:
You can manipulate (copy) all types of files
Byte buffer stream:
Can improve efficiency
The file cannot be operated directly, and the byte stream needs to be passed

There are four ways to copy files:
The byte stream reads and writes one byte at a time
Byte stream reads and writes one byte array at a time
The byte buffer stream operates one byte at a time
The byte buffer stream operates one byte array at a time

Character stream - encoding table

Code: character to number
Decoding: converting numbers into characters
Code table: a table of correspondence between characters and numbers
Character set: a set of characters corresponding to a coding table

What are the common coding tables?
ASCII: Modern English, USA
GB2312: Simplified Chinese, 7000 characters
gbk: more than 20000 characters, compatible with GB2312
gb18030: the most complete code table in Chinese, including minority languages
iso-8859-1: European code, Latin alphabet
unicode code table: universal code, the written characters of major national languages in the world
utf-8: variable length, English one, other two, Chinese three, up to 4 bytes
utf-16: fixed length, 2 bytes, 4 bytes
utf-32: fixed 4 bytes

code:
byte[] getBytes(): encode the String into a series of bytes using the platform default character set. There are array types
byte[] getBytes(String charseName): encode the String using the character set specified above

decode:
String(byte[] bytes): decode the specified byte array through the default character set to construct a new string
String(byte[] bytes, String charsetName): decode through the specified character set

public class Main {
    public static void main(String[] args) throws IOException {
        byte[] b1 = "I'm so handsome".getBytes();
        System.out.println(Arrays.toString(b1));

        byte[] b2 = "I'm so handsome".getBytes("GBK");
        System.out.println(Arrays.toString(b2));

        String s1 = new String(b1);
        System.out.println(s1);

        String s2 = new String(b2,"GBK");
        System.out.println(s2);

        String s3= new String(b2,"UTF-8");
        System.out.println(s3);
    }
}

Execution results:

Character stream - write out data

Steps:
Create character output stream object
If the file does not exist, create it, but ensure that the parent path exists.
If the file exists, the parameter is whether to empty it.

Write data
The data of type int written out is actually the letter corresponding to the integer on the code table.
Writing out string data is to write out the string itself as it is.

Release resources

Introduction: (bottom layer: byte stream + encoding table)
Writer: Abstract parent class used to write character stream
FileWriter: a common subclass used to write character streams

Construction method

Method name

Explain

            FileWriter (File file)Construct a FileWriter object based on the given File object
FileWriter (File file, boolean append)Construct a FileWriter object based on the given File object
        FileWriter (String fileName)Construct a FileWriter object according to the given file name

                FileWriter

  (String fileName, boolean append)

Based on the given file name and indicating whether to attach write data

To construct the FileWriter object

Member method

Method name

Explain

        void write (int c)Write a character
        void write (char[] cbuf)Write a character array
        void write (char[] cbuf, int off, int len)Writes part of a character array
        void write (String str)Write a string
        void write (String str, int off, int len)Write part of a string
public class Main {
    public static void main(String[] args) throws IOException {
        File f = new File("src/a.txt");
        FileWriter fw = new FileWriter(f,true);

        int n1 = 97;
        fw.write(n1);

        char[] n2 = {'\r','a','b','c','d'};
        fw.write(n2);

        fw.write(n2,0,4);

        String s = "\r Chinese table tennis nb";
        fw.write(s);

        fw.write(s,0,5);
        fw.close();
    }
}

Execution results:

Method name

Explain

                flush ()Brush the new stream and continue to write data
                close ()

Close the stream to release resources, but brush a new stream before closing.

Once closed, no more data can be written

Character stream - read data

Construction method

Method name

Explain

        FileReader(File file)Create a new FileReader given the File from which to read data
        FileReader(String fileName)Create a new FileReader given the file name from which to read data

Member method

Method name

Explain

                int read ()Read data one character at a time
                int read (char[] cbuf)Read one character array data at a time
public class Main {
    public static void main(String[] args) throws IOException {
        File f = new File("src/a.txt");
        FileReader fr = new FileReader(f);

        int len;
        while ((len = fr.read()) != -1){
            System.out.print((char)len);
        }

        char[] chars = new char[1024];
        int len2;
        while ((len2 = fr.read(chars)) != -1){
            System.out.print(new String(chars,0,len2));
        }
        fr.close();
    }
}

Execution code:

Buffer stream

BufferedWriter: writes text to the character output stream and buffers characters to provide efficient writing of single characters, arrays and strings. You can specify the buffer size or accept the default size. The default value is large enough for most purposes

BufferedReader: reads text from the character input stream and buffers characters to provide efficient reading of characters, arrays and rows. You can specify the buffer size or use the default size. The default value is large enough for most purposes

Construction method

Method name

Explain

        BufferedWriter (Writer out)Create character buffered output stream object
        BufferedReader (Reader in)Create character buffered input stream object

Unique member method

Method name

Explain

                void newLine ()Write a line separator. The line separator string is defined by the system property

Method name

Explain

                String readLine ()

Read a line of text. The result is a string containing the contents of the line, excluding any

Line termination character null if the end of the stream has been reached

public class Main {
    public static void main(String[] args) throws IOException {
        File f = new File("src/a.txt");
        BufferedWriter bw = new BufferedWriter(new FileWriter(f));
        bw.write("Your girlfriend is so beautiful");
        bw.newLine();
        bw.write("No wonder you don't have a girlfriend at all");
        bw.close();

        BufferedReader br = new BufferedReader(new FileReader(f));
        String line;
        while ((line = br.readLine()) != null){
            System.out.println(line);
        }
        br.close();
    }
}

Execution results:

Conversion flow

InputStreamReader: it is a bridge from byte stream to character stream. The parent class is Reader. It reads bytes and decodes them into characters using the specified encoding. The character set it uses can be specified by name or explicitly, or it can accept the default character set of the platform

OutputStreamWriter: it is a bridge from character stream to byte stream. The parent class is the Writer that uses the specified encoding to encode the written characters into bytes. The character set it uses can be specified by name or explicitly, or it can accept the default character set of the platform

Construction method (required before JKD 11)

Method name

Explain

InputStreamReader(InputStream in)Create an InputStreamReader object using the default character encoding
InputStreamReader(InputStream in,String chatset)Creates an InputStreamReader object using the specified character encoding
OutputStreamWriter(OutputStream out)Creates an OutputStreamWriter object using the default character encoding
OutputStreamWriter(OutputStream out,String charset)Creates an OutputStreamWriter object using the specified character encoding
public class Main {
    public static void main(String[] args) throws IOException {
        InputStreamReader isr = new InputStreamReader(new FileInputStream("D:/a.txt"),"utf-8");
        char[] chars = new char[1024];
        ArrayList<String> al = new ArrayList<>();
        int len;
        while ((len = isr.read(chars)) != -1){
            al.add(new String(chars));
        }
        isr.close();

        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("D:/a.txt"),"gbk");
        for (String s : al) {
            osw.write(s);
        }
        osw.close();
    }
}

Object operation flow

Object serialization:
Convert objects into byte sequences (stored on disk or transmitted over the network)
         ObjectOutputStream(OutputStream)
Object deserialization:
Read byte sequence and return an object (byte sequence can come from file or network)

Steps for serialization
    1. Create ObjectOutputStream(OutputStream)
    2. Create object (Student object)
    3.writeObject(stu);
    4. Close flow

be careful:
    1. The class of the serialized object must implement Serializable
    2. If a member variable does not want to be serialized, it can be modified with the transient keyword

Construction method and serialization method

Method name

Explain

        ObjectOutputStream(OutputStream out)Creates an ObjectOutputStream that writes to the specified OutputStream
               void writeObject (Object obj)Writes the specified object to ObjectOutputStream

Method name

Explain

           ObjectInputStream(InputStream in)Creates an ObjectInputStream read from the specified InputStream
                        Object readObject ()Read an object from ObjectInputStream
public class Main {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        User user = new User("zhangsan","fawaikuangtu");
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src/a.txt"));
        oos.writeObject(user);
        oos.close();

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src/a.txt"));
        User us = (User) ois.readObject();
        System.out.println(us);
    }
}

Execution results:

Properties

summary:
Is a collection class of Map system
Properties can be saved to or loaded from a stream
Each key in the attribute list and its corresponding value is a string

Unique method

Method name

Explain

        Object setProperty (String key, String value)

Set the key and value of the collection, both of which are of String type,

The bottom layer calls the Hashtable put method

        String getProperty (String key)Search for attributes using the key specified in this attribute list
        Set<String> stringPropertyNames ()

Returns a non modifiable value from the property list

Key set, where the key and its corresponding value are strings

public class Main {
    public static void main(String[] args) {
        Properties prop = new Properties();
        prop.setProperty("little dragon maiden", "Guo Yang");
        System.out.println(prop);

        String value = prop.getProperty("little dragon maiden");
        System.out.println(value);

        Set<String> strings = prop.stringPropertyNames();
        for (String string : strings) {
            String value2 = prop.getProperty(string);
            System.out.println(string + " " + value2);
        }
    }
}

Execution results:

Properties-load,store

Method combined with IO stream

Method name

Explain

        void load (Reader reader)Read the attribute list (key and element pairs) from the input character stream
        void store (Writer writer, String comments)Write this list of Properties (key and element pairs) to this Properties table and write the output character stream in a format suitable for using the load(Reader) method
public class Main {
    public static void main(String[] args) throws IOException {
        Properties prop = new Properties();
        prop.put("wo","n");
        prop.put("hao","0");
        prop.put("shuai","1");
        FileWriter fw = new FileWriter("src/demo1/prop.properties");
        prop.store(fw,"I'm a comment");
        fw.close();

        Properties prop2 = new Properties();
        FileReader fr = new FileReader("src/demo1/prop.properties");
        prop2.load(fr);
        fr.close();
        System.out.println(prop2);
    }
}

Execution results:

Keywords: JavaEE

Added by Sphen001 on Wed, 29 Dec 2021 17:40:10 +0200