当前位置:网站首页>11 IO frame

11 IO frame

2022-06-26 05:19:00 Air transport Alliance

1. The concept and classification of flow

1.1 Concept

Concept : Memory And The storage device Between To transmit data Of passageway .

1.2 classification

  • In the direction of 【 a key 】
    • Input stream : take The storage device The content in Read in To Memory in
    • Output stream : take Memory The content in write in To The storage device in

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-iffNlDcp-1642148739563)(…/AppData/Roaming/Typora/typora-user-images/image-20220108204025495.png)]

  • By unit

    • Byte stream : In bytes . Can read and write all data ( Because all data is stored in bytes )
    • Character stream : In characters , Only text data can be read and written
  • Press function

    • Node flow : With actual transmission data Reading and writing function
    • Filter flow : Enhanced functionality based on node flow

2. Byte stream

  • The parent of the byte stream ( abstract class )
    • InputStream: Byte input stream
    • OutputStream: Byte output stream

image-20220108205543476

Because the number of parent classes is abstract , To use, you must use its subclasses .

2.1 File byte stream

  • FileInputStream:— Realized InputStream abstract class
    • public int read(byte[] b)// Read multiple bytes from the stream , Save the read content to b Array , Returns the number of bytes actually read ; If it reaches the end of the file , Then return to -1
    • Construction method : Pass in the file name path
  • FileOutputStream:— Realized OutputStream abstract class
    • public void write(byte[] b)// Write multiple bytes at a time , take b All the bytes in the array , Write output stream .

(1) File byte input stream case :

package com.song.demo01;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

//FileInputStream class , File byte input stream 
public class demo01 {
    
    public static void main(String[] args) throws IOException {
    
        //1. establish FileInputStream
        FileInputStream fis = new FileInputStream("d:\\aaa.txt");

        //2. Read the file 
        //2.1 Single byte read 
        //fis.read() Only one byte can be read at a time ( Read out the corresponding characters Ascii code ), Read to the end and return to -1
        /*int data = 0; while ((data = fis.read()) != -1) { System.out.println((char) data); }*/

        //2.2 Read multiple bytes at a time ( File is written to abcdefgh)
        /*byte[] b1 = new byte[3]; int count1 = fis.read(b1);// What is returned is the actual number of reads  System.out.println(count1); System.out.println(new String(b1));//abc byte[] b2 = new byte[5]; int count2 = fis.read(b2);// What is returned is the actual number of reads  System.out.println(count2); System.out.println(new String(b2));//defgh */
        // Implemented by loop 
        byte[] b = new byte[3];
        int count = 0;
        while ((count = fis.read(b)) != -1) {
    
            System.out.println(new String(b, 0, count));
        }
        // Three times abc,def,gh

        //3. close 
        fis.close();
    }
}

(2) File byte output stream case :

package com.song.demo01;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

//FileOutputStream File byte output stream 
public class demo02 {
    
    public static void main(String[] args) throws IOException {
    
        //1. Create file byte outflow object 
        FileOutputStream fos = new FileOutputStream("d://bbb.txt");// Each time, the original 
        //FileOutputStream fos = new FileOutputStream("d://bbb.txt", true);//append=true, Indicates that... Will be appended , Will not overwrite the original 


        //2. write file 
        //2.1 Single write 
        /*fos.write(97);// Is written Asci Corresponding characters  fos.write('b'); fos.write('c');*/
        //2.2 Write once 
        String str = "Hello World!";
        fos.write(str.getBytes());// Get the byte array corresponding to the string , Write again 

        //3. close 
        fos.close();

    }
}

(3) The case of file copying :

package com.song.demo01;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

// Use byte stream to copy files 
public class demo03 {
    
    public static void main(String[] args) throws IOException {
    
        //1. Create stream 
        //1.1 File byte input stream 
        FileInputStream fis = new FileInputStream("d://a.jpg");
        //1.2 File byte output stream 
        FileOutputStream fos = new FileOutputStream("d://b.jpg");
        //2. Read and write 
        byte[] buf = new byte[1024];//1KB  The buffer 
        int count = 0;// Save the number of bytes actually read 
        while ((count = fis.read(buf)) != -1) {
    
            fos.write(buf, 0, count);
        }
        //3. close 
        fis.close();
        fos.close();
        System.out.println(" Copy off ");

    }
}

2.2 Byte buffer stream

Buffer flow :BufferInputStream/BufferOutputStream

  • Improve IO efficiency , Reduce the number of disk accesses
  • The data is stored in a buffer ,flush Is to write the contents of the cache to a file , It can also be direct close
  • The internal essence of buffer stream is to maintain byte stream

( The efficiency of file byte stream is low , Byte buffers are more efficient )

(1) Use byte buffer stream to read file cases

package com.song.demo01;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class demo04 {
    
    public static void main(String[] args) throws IOException {
    
        //1. establish BufferInputStream
        // Buffered byte input stream 
        FileInputStream fis = new FileInputStream("d:\\aaa.txt");
        BufferedInputStream bis = new BufferedInputStream(fis);
        //2. Read 
        // Use the system's own buffer 8KB
        /*int data = 0; //bis One read of , Can read cache 8KB, Read directly from the buffer next time  while ((data = bis.read()) != -1) { System.out.print((char) data); }*/
        // Custom buffer 
        byte[] buf = new byte[1024];//1KB The buffer 
        int count = 0;
        while ((count = bis.read(buf)) != -1) {
    
            System.out.println(new String(buf, 0, count));
        }

        //3. close ( Just close the buffer stream , You can turn off the byte stream at the same time )
        bis.close();

    }
}

(2) Use byte buffer stream to write file cases

package com.song.demo01;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class demo05 {
    
    public static void main(String[] args) throws IOException {
    
        //1. establish BufferedOutputStream
        // You can write to a buffer first , Again flush To the bottom , You don't have to write to the underlying layer every time 
        FileOutputStream fos = new FileOutputStream("d:\\buffer.txt");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        //2. write file 
        //8KB The buffer 
        for (int i = 0; i < 10; i++) {
    
            bos.write("Hello World!\n".getBytes());// Here is just writing to the buffer , Not directly written to the file 
            bos.flush();// Refresh write to hard disk 
        }
        //3. close ( Internally it will call flush)
        bos.close();


    }
}

2.3 Object flow

Object flow :ObjectOutputStream/ObjectInputStream

Object flow is filter flow , Create a node flow before using .

  • Enhanced buffer functionality
  • Enhanced literacy 8 Basic data types and string functions
  • Enhanced the function of reading and writing objects
    • readObject() Read an object from the stream
    • writeObject(Object obj) Write an object to the stream

The process of streaming objects is called serialization 、 Deserialization .

(1) serialize

  • requirement : Serialized classes must implement Serializable Interface
  • Use ObjectOutputStream Implement serialization ( Write an object )
package com.song.demo01;

import java.io.Serializable;

// Object to serialize , Class must implement an interface Serializable--- Just mark that the class can be serialized 
public class Student implements Serializable {
    

    //serialVersionUID: Serialized version number ID, effect : Ensure that the serialized class and the deserialized class are the same class .
    private static final long serialVersionUID = 100L;

    private String name;
    private int age;

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

    public String getName() {
    
        return name;
    }

    public int getAge() {
    
        return age;
    }

    public void setName(String name) {
    
        this.name = name;
    }

    public void setAge(int age) {
    
        this.age = age;
    }

    @Override
    public String toString() {
    
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
package com.song.demo01;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

// Use ObjectOutputStream Implement object serialization 
// requirement : Object to serialize , Class must implement an interface Serializable
public class demo06 {
    
    public static void main(String[] args) throws Exception {
    
        //1. Create an object stream 
        FileOutputStream fos = new FileOutputStream("d:\\student.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        //2. Implement serialization ( Write operation )
        // requirement : Object to serialize , Class must implement an interface Serializable
        Student zhangsan = new Student("zhangsan", 20);
        oos.writeObject(zhangsan);// Write an object to 
        //3. close (clos Automatically called flush)
        oos.close();
        System.out.println(" Serialization complete ");


    }
}

(2) Deserialization

  • Use ObjectInputStream Implement deserialization – Read from the file and reconstruct the object
package com.song.demo01;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

// Use ObjectInputStream Implement deserialization 
public class demo07 {
    
    public static void main(String[] args) throws Exception {
    
        //1. Create an object stream 
        FileInputStream fis = new FileInputStream("d:\\student.txt");
        ObjectInputStream ois = new ObjectInputStream(fis);
        //2. Read the file ( Deserialization )
        Student student = (Student) ois.readObject();// Strong conversion 
        System.out.println(student.toString());
        //3. close 
        ois.close();
        System.out.println(" Deserialization complete ");
    }
}

(3) Serialization and deserialization considerations

  • Serialized classes must implement Serializable Interface

  • Object properties in serialized classes ( class ) It also requires that Serializable Interface

  • serialVersionUID: Serialized version number ID, effect : Ensure that the serialized class and the deserialized class are the same class .( To ensure that the ID)

  • Use transient( Instantaneous instantaneous ) Modify properties , This property cannot be serialized

     private transient int age;// This property cannot be serialized 
    
  • Static attribute (static) It cannot be serialized

  • When serializing multiple objects , Can be achieved by means of collections ----ArrayList

package com.song.demo01;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;

// Use ObjectOutputStream Implement object serialization 
// requirement : Object to serialize , Class must implement an interface Serializable
public class demo06 {
    
    public static void main(String[] args) throws Exception {
    
        //1. Create an object stream 
        FileOutputStream fos = new FileOutputStream("d:\\student.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        //2. Implement serialization ( Write operation )
        // requirement : Object to serialize , Class must implement an interface Serializable
        Student zhangsan = new Student("zhangsan", 20);
        Student lisi = new Student("lisi", 22);
        ArrayList<Student> list = new ArrayList<>();
        list.add(zhangsan);
        list.add(lisi);
        oos.writeObject(list);// Write an object to 
        //3. close (clos Automatically called flush)
        oos.close();
        System.out.println(" Serialization complete ");


    }
}
package com.song.demo01;

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Arrays;

// Use ObjectInputStream Implement deserialization 
public class demo07 {
    
    public static void main(String[] args) throws Exception {
    
        //1. Create an object stream 
        FileInputStream fis = new FileInputStream("d:\\student.txt");
        ObjectInputStream ois = new ObjectInputStream(fis);
        //2. Read the file ( Deserialization )
        ArrayList<Student> list = (ArrayList<Student>) ois.readObject();// Strong conversion 
        System.out.println(list.toString());
        //3. close 
        ois.close();
        System.out.println(" Deserialization complete ");
    }
}

4. Character encoding

image-20220109143559707

  • ISO-8859-1: In one byte , At most 256 Characters

  • UTF-8: Generally used internationally , use 1 or 2 or 3 Byte representation

  • GB2312: chinese , use 1 or 2 Byte representation

  • GBK: It's a national standard 2312 The upgrade , use 1 or 2 Byte representation

When the encoding method is inconsistent with the decoding method , There will be garbled code ! Pay attention to consistency .

4. Character stream

example :( There is a problem reading Chinese characters using byte stream )

package com.song.demo02;

import java.io.FileInputStream;

// Use the file byte input stream to read an object 
public class demo01 {
    
    public static void main(String[] args) throws Exception {
    
        //1. establish FileInputStream object 
        FileInputStream fis = new FileInputStream("d:\\aaa.txt");// In file : study hard 
        //2. Read 
        int data = 0;
        while ((data = fis.read()) != -1) {
    // In file 12 Bytes 4 The Chinese characters ; And here read Is to read bytes one by one , Into characters , Therefore, there are problems 
            System.out.print((char) data);// Read Chinese directly , Garbled 
        }
        //3. close 
        fis.close();
    }
}

The parent of character stream ( abstract class )

  • Reader: Character input stream
  • Writer: Character output stream

image-20220109144925316

Because the number of parent classes is abstract , To use, you must use its subclasses .

4.1 File character stream

  • FileReader:
    • public int read(char[] c)// Read multiple characters from the stream , Save what you read into c Array , Returns the number of characters actually read ; If you reach the end of the file , Then return to -1.
    • FileReader Class assumes that the default character encoding and byte buffer size are appropriate , To specify these values yourself , Can now FileInputStream Construct a InputStreamReader.
  • FileWriter:
    • public void write(String str)// Write more than one character at a time , take b All characters in the array , Write output stream .

(1) File character input stream

package com.song.demo02;

import java.io.FileReader;

public class demo02 {
    
    public static void main(String[] args) throws Exception {
    
        //1. Create a file character output stream FileReader
        FileReader fr = new FileReader("d:\\aaa.txt");
        //2. Read 
        //2.1 Single character read 
        /*int data = 0; while ((data = fr.read()) != -1) {// here read What is read is a character , Not a byte , It may correspond to three bytes  System.out.print((char) data); }*/
        //2.2 Read more than one character at a time through the character buffer 
        char[] buf = new char[1024];// establish 1K The buffer , Here is the character array , Not a byte array , Pay attention to distinguish between !!
        int count = 0;
        while ((count = fr.read(buf)) != -1) {
    
            System.out.println(new String(buf, 0, count));
        }

        //3. close 
        fr.close();
    }
}

(2) File character output stream

package com.song.demo02;

import java.io.FileWriter;

public class demo03 {
    
    public static void main(String[] args) throws Exception {
    
        //1. Create a file character output stream object FileWriter
        FileWriter fw = new FileWriter("d:\\test.txt");
        //2. write in 
        for (int i = 0; i < 10; i++) {
    
            fw.write("Java  Is the best language in the world !!\n");
            fw.flush();
        }
        //3. close 
        fw.close();
    }
}

(3) Use file character stream to copy files

package com.song.demo02;

import java.io.FileReader;
import java.io.FileWriter;

// Use file character stream to copy files -- Only text files can be copied , You can't copy binary files like pictures 
public class demo04 {
    
    public static void main(String[] args) throws Exception {
    
        //1. Create stream 
        FileReader fr = new FileReader("d:\\test.txt");
        FileWriter fw = new FileWriter("d:\\test2.txt");
        //2. Read and write 
        int data = 0;
        while ((data = fr.read()) != -1) {
    
            fw.write(data);
        }
        //3. close 
        fr.close();
        fw.close();
        System.out.println(" Copy complete ");

    }
}

Character streams can only be used for text files , Cannot be used for binary files such as pictures .

Picture is not encoded , Write in characters , It's a mess of code . Therefore, the character stream cannot copy files without character encoding .

Using byte stream, you can copy any file , Because all the files on the hard disk are stored in binary form .

4.2 Character buffer stream

Buffer flow :BufferReader/BufferWriter

  • Efficient reading and writing
  • Support input line feed
  • You can write one line at a time 、 Read a line

(1) Use the character buffer stream to read

package com.song.demo02;

import java.io.BufferedReader;
import java.io.FileReader;

// Use the character buffer stream to read the file 
public class demo05 {
    
    public static void main(String[] args) throws Exception {
    
        //1. Create character buffer stream 
        FileReader fr = new FileReader("d:\\test.txt");
        BufferedReader br = new BufferedReader(fr);
        //2. Read 
        //2.1 The first way 
        /*char[] buf=new char[1024]; int count=0; while((count=br.read(buf))!=-1){ System.out.print(new String(buf,0,count)); }*/
        //2.2 Line by line reading 
        String line = null;
        while ((line = br.readLine()) != null) {
    
            System.out.println(line);
        }
        //3. close 
        br.close();

    }
}

(2) Use character buffer stream to write

package com.song.demo02;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;

// Write to file using character buffer stream 
public class demo06 {
    
    public static void main(String[] args) throws Exception {
    
        //1. Create objects 
        FileWriter fw = new FileWriter("d:\\tt.txt");
        BufferedWriter bw = new BufferedWriter(fw);
        //2. write in 
        for (int i = 0; i < 10; i++) {
    
            bw.write(" study hard , Day day up ");// No line breaks 
            bw.newLine();// Write a newline character \r\n
            bw.flush();
        }
        //3. close 
        bw.close();
        System.out.println(" completion of enforcement ");
    }
}

5. Print stream

PrintWriter– Inherited Writer class :

  • Encapsulates the print() 、println() Method , Support line wrapping after writing
  • Support data printing as is — Richer data types supported
package com.song.demo02;

import java.io.PrintWriter;

//PrintWrite
public class demo07 {
    
    public static void main(String[] args) throws Exception {
    
        //1. Create a print stream 
        PrintWriter pw = new PrintWriter("d:\\print.txt");
        //2. Print 
        pw.println(97);
        pw.println(true);
        pw.println(3.14);
        pw.println('a');
        //3. close 
        pw.close();
    }
}

6. Converted flow

  • The bridge transforms the flow :InputStreamReader/OutputStreamWriter
    • You can convert a byte stream to a character stream ; Characters flow into byte stream ( Conversion between characters in memory and bytes in hard disk )
    • You can set the encoding of characters .

(1)InputStreamReader Read the file

  • Bytes flow into a stream of characters
  • InputStreamReader In fact, the abstract classes of byte stream and character stream are combined .
package com.song.demo02;

import java.io.FileInputStream;
import java.io.InputStreamReader;

//InputStreamReader Read the file , You can specify the encoding to use 
public class demo08 {
    
    public static void main(String[] args) throws Exception {
    
        //1. Create objects 
        FileInputStream fis = new FileInputStream("d:\\test.txt");
        InputStreamReader isr = new InputStreamReader(fis, "utf-8");// The document is actually utf-8 Coding method of ;
        // Ensure that the file code is consistent with the conversion stream code used 
        //FileReader Code cannot be specified ;InputStreamReader You can specify the code 

        //2. Read the file 
        int data = 0;
        while ((data = isr.read()) != -1) {
    
            System.out.print((char) data);
        }
        //3. close 
        isr.close();
    }
}

(2)OutputStreamWriter write file

  • Characters flow into byte stream
  • OutputStreamWriter In fact, the abstract classes of byte stream and character stream are combined .
package com.song.demo02;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

// Use OutputStreamWriter write file 
public class demo09 {
    
    public static void main(String[] args) throws Exception {
    
        //1. Create stream 
        FileOutputStream fos = new FileOutputStream("d:\\test3.txt");// Byte output stream 
        OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");// Custom encoding 
        //2. write in 
        for (int i = 0; i < 10; i++) {
    
            osw.write(" Study hard !\n");
            osw.flush();
        }
        //3. close 
        osw.close();
    }
}

7.File class

Operations related to file reading and writing can be performed with the help of streams , Other similar deletion 、 Time and other operations need the help of File class

Concept : Represents a file or folder in the physical drive letter .

File Class is an abstract representation of file and directory names .

image-20220109171014594

7.1 File operation and folder operation

package com.song.demo02;

import java.io.File;
import java.util.Date;

/** * File The use of the class : * (1) Separator  * (2) File operations  * (3) Folder operation  */
public class demo10 {
    
    public static void main(String[] args) throws Exception {
    
        separator();
        fileOpe();
        directorOpe();

    }

    //(1) Separator 
    public static void separator() {
    
        System.out.println(" Path separator :" + File.pathSeparator);// ;
        System.out.println(" Name separator :" + File.separator);// \
    }

    //(2) File operations 
    public static void fileOpe() throws Exception {
    
        //1. create a file 
        //1.1 Create a file object 
        File file = new File("d:\\file.txt");// The file does not necessarily exist in the actual hard disk 
        //1.2 Create file on hard disk 
        if (!file.exists()) {
    
            boolean b = file.createNewFile();// If the file exists, it will not be created ; Create if it does not exist 
            System.out.println(" Create results :" + b);
        }

        //2. Delete file 
        /* //2.1 Delete directly  System.out.println(" Delete result :" + file.delete()); //2.2 Use JVM Delete on exit  file.deleteOnExit();// Only JVM Delete only when exiting  Thread.sleep(5000);*/

        //3. Get file information 
        //3.1 Get the absolute path of the file 
        System.out.println(" Get the absolute path of the file :" + file.getAbsolutePath());
        //3.2 Get path 
        System.out.println(" Get path :" + file.getPath());// It is related to the customized path , If you write absolute path, use absolute path ; If you write relative paths, use relative paths 
        //3.3 Get the file name 
        System.out.println(" Get the file name :" + file.getName());
        //3.4 Get parent directory 
        System.out.println(" Get file parent directory :" + file.getParent());
        //3.5 Get file length 
        System.out.println(" Get file length :" + file.length());
        //3.6 Get file creation time 
        System.out.println(" Get file creation time :" + new Date(file.lastModified()).toLocaleString());

        //4. Judge 
        System.out.println(" Judge whether the document is writable :" + file.canWrite());
        System.out.println(" Determine if it's a document :" + file.isFile());
        System.out.println(" Whether the file is hidden :" + file.isHidden());
    }

    //(2) Folder operation 
    public static void directorOpe() throws Exception {
    
        //1. Create folder 
        File dir = new File("d:\\a\\b\\c");
        if (!dir.exists()) {
    
            //dir.mkdir();// Only single level directories can be created 
            //dir.mkdirs();// You can create multi-level directories 
            System.out.println(" Create results :" + dir.mkdirs());
        }

        //2. Delete folder 
        /* //2.1 Delete directly  System.out.println(" Delete result :" + dir.delete());// Not all deleted , Delete only the bottom layer c Catalog , And ask for c Must be an empty directory ! //2.2 Use JVM Delete  dir.deleteOnExit();*/

        //3. Get folder information 
        System.out.println(" Get absolute path " + dir.getAbsolutePath());
        System.out.println(" Get path " + dir.getPath());
        System.out.println(" Get folder name " + dir.getName());// Just the bottom 
        System.out.println(" Get parent directory " + dir.getParent());
        System.out.println(" Get creation time " + new Date(dir.lastModified()).toString());

        //4. Judge 
        System.out.println(" Determine whether it is a folder " + dir.isDirectory());
        System.out.println(" Determine whether it is hidden " + dir.isHidden());

        //5. Traversal folder 
        File dir2 = new File("d:\\software");
        String[] files = dir2.list();
        for (String str : files) {
    
            System.out.println(str);
        }


    }

}

7.2FileFilter Interface

  • public interface FileFilter

    • boolean accept(File pathname)
  • When calling File Class listFiles() When the method is used , Support incoming FileFilter Interface implementation class , Filter the obtained file , Only files that meet the conditions can appear in listFiles() In the return value of .

        //FileFilter Use 
        // Notice here is File[]  aggregate 
        File[] files2 = dir.listFiles(new FileFilter() {
    
            @Override
            public boolean accept(File pathname) {
    
                //return false;// The default is false, Remove all documents 
                if (pathname.getName().endsWith(".jpg")) {
    
                    return true;// Only keep jpg file 
                }
                return false;
            }
        });
        for (File file : files2) {
    
            System.out.println(file.getName());
        }

7.3 Recursive traversal and recursive deletion

(1) Recursively traversing folders

package com.song.demo02;


import java.io.File;

// Case a : Recursively traversing folders 
public class demo11 {
    
    public static void main(String[] args) {
    
        File dir = new File("d:\\software");
        listDir(dir);
    }

    public static void listDir(File dir) {
    
        File[] files = dir.listFiles();
        System.out.println(dir.getAbsolutePath());
        if (files != null && files.length > 0) {
    
            for (File file : files) {
    
                if (file.isDirectory()) {
    
                    listDir(file);// recursive 
                } else {
    
                    System.out.println(file.getName());
                }
            }
        }

    }
}

(2) Recursively delete folders

package com.song.demo02;

import java.io.File;

// Case 2 : Recursively delete folders 
public class demo12 {
    
    public static void main(String[] args) {
    
        delDir(new File("d:\\a"));
    }

    public static void delDir(File dir) {
    
        File[] files = dir.listFiles();
        if (files != null && files.length > 0) {
    
            for (File file : files) {
    
                if (file.isDirectory()) {
    
                    delDir(file);
                } else {
    
                    // Delete file 
                    System.out.println(file.getAbsolutePath() + " Delete :" + file.delete());
                }
            }
            // Delete folder 
            System.out.println(dir.getAbsolutePath() + " Delete :" + dir.delete());
        }
    }
}

Add :Properities

  • Properities: Attribute set
  • characteristic :
    1. Store property name and property value
    2. Both the property name and the property value are of string type
    3. There is no generic
    4. It's about flow
package com.song.demo02;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.Set;

//Properities Use of collections 
public class demo13 {
    
    public static void main(String[] args) throws Exception {
    
        //1. Create set 
        Properties properties = new Properties();
        //2. Add data 
        properties.setProperty("name", "zhangsan");
        properties.setProperty("age", "18");
        System.out.println(properties.toString());
        //3. Traverse 
        //3.1----keyset---
        //3.2----entryset---
        //3.3----stringPropertyNames---
        Set<String> pronames = properties.stringPropertyNames();
        for (String pro : pronames) {
    
            System.out.println(pro + "====" + properties.getProperty(pro));

        }

        //4. Methods related to flow 

        //4.1----list----
        /*PrintWriter pw = new PrintWriter("d:\\print2.txt"); properties.list(pw); pw.close();*/

        //4.2----store--- preservation 
        /*FileOutputStream fos = new FileOutputStream("d:\\store.properites"); properties.store(fos, " notes "); fos.close();*/

        //4.3----load--- load 
        Properties properties2 = new Properties();
        FileInputStream fis = new FileInputStream("d:\\\\store.properites");
        properties2.load(fis);
        fis.close();
        System.out.println(properties.toString());


    }
}

summary

  • The concept of flow :

    A channel for transferring data between memory and storage devices

  • Classification of flows :

    Input stream 、 Output stream ; Byte stream 、 Character stream ; Node flow 、 Filter flow

  • Serialization and deserialization

    Objects in memory are written to hard disk files through streaming — serialize

    The objects in the hard disk file are read into the memory through the stream — Deserialization

  • File class

    Represents a file or folder in the physical drive letter

原网站

版权声明
本文为[Air transport Alliance]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202180507299746.html