java Foundation (25):Properties, Serialization Stream, Print Stream, commons-IO

Keywords: Java

1. Properties class

1.1 Introduction to Properties Class

The Properties class represents a persistent set of attributes. Properties can be stored in or loaded from a stream. Each key and its corresponding value in the property list is a string.

Characteristic:

1. Subclasses of Hashtable and methods in map sets can be used.

2. The set has no generics. The key values are all strings.

3. It is a persistent set of attributes. Keys can be stored in collections or on persistent devices (hard disks, U disks, CD-ROMs). The source of key values can also be a persistent device.

4. Combination of existing and streaming technologies.

load(InputStream) reads the data from the file corresponding to the specified stream and saves it in the Propertie collection

load(Reader)  

Store (Output Stream, commonts) stores the data in the collection into the file corresponding to the specified stream, and the parameter commonts represents the description information.

stroe(Writer,comments);

Code demonstration:

/*
 * 
 * Properties Collection, which is the only collection that can interact with IO flows
 * 
 * Requirements: Add elements to the Properties collection and traverse
 * 
 * Method:
 * public Object setProperty(String key, String value)Call the Hashtable method put.
 * public Set<String> stringPropertyNames()Returns the key set in this property list.
 * public String getProperty(String key)Search for properties in this property list with the specified key
 */
public class PropertiesDemo01 {
    public static void main(String[] args) {
        //Creating Collection Objects
        Properties prop = new Properties();
        //Add elements to collections
        //prop.put(key, value);
        prop.setProperty("Xun Zhou", "Jacky Cheung");
        prop.setProperty("Li Xiaolu", "Jia Nailiang");
        prop.setProperty("Yang Mi", "Hawick Lau");
        
        //System.out.println(prop);//Use of tests
        //Ergodic set
        Set<String> keys = prop.stringPropertyNames();
        for (String key : keys) {
            //Find values by keys
            //prop.get(key)
            String value = prop.getProperty(key);
            System.out.println(key+"==" +value);
        }
    }
}

1.2 Store content in a collection into a file

Requirements: Use Properties collection to complete the operation of storing the contents of the collection into the corresponding files of the IO stream

Analysis:

1. Create Properties Collection

2. Add elements to collections

3. Create streams

4. Store the data in the collection in the file corresponding to the stream

  stroe(Writer,comments)

  store(OutputStream,commonts)

Save the data in the collection to the file corresponding to the specified stream. The parameter commonts represent the description information.

5. Close the flow

 

Code demonstration:

public class PropertiesDemo02 {
    public static void main(String[] args) throws IOException {
        //1,Establish Properties aggregate
        Properties prop = new Properties();
        //2,Add elements to collections
        prop.setProperty("Xun Zhou", "Jacky Cheung");
        prop.setProperty("Li Xiaolu", "Jia Nailiang");
        prop.setProperty("Yang Mi", "Hawick Lau");
        
        //3,Create stream
        FileWriter out = new FileWriter("prop.properties");
        //4,Store the data in the collection in the file corresponding to the stream
        prop.store(out, "save data");
        //5,Closed flow
        out.close();
    }
}

1.3 Read the data in the file and save it to the collection

Requirements: Extract data from the property set file prop.properties and store it in the collection

Analysis:

1. Create a collection

2. Create stream objects

3. Read the data from the file corresponding to the stream into the collection

load(InputStream) reads the data from the file corresponding to the specified stream and saves it in the Propertie collection

  load(Reader)  

4, close the flow.

5. Display the data in the collection

Code demonstration:

public class PropertiesDemo03 {
    public static void main(String[] args) throws IOException {
        //1,Create set
        Properties prop = new Properties();
        //2,Create stream objects
        FileInputStream in = new FileInputStream("prop.properties");
//FileReader in = new FileReader("prop.properties");
        //3,Read the data from the file corresponding to the stream into the collection
        prop.load(in);
        //4,Closed flow
        in.close();
        //5,Display data in a collection
        System.out.println(prop);
        
    }
}

Note: FileReader can complete the Chinese reading operation in the file.

2. Serialized stream and deserialized stream

For reading objects from the stream

Operational flow ObjectInputStream is called deserialized flow

ObjectOutputStream, an operation flow used to write objects to a stream, is called a serialized stream

Features: Used for manipulating objects. Objects can be written to or read from a file.

2.1 Object Output Stream, Object Serialization Stream

ObjectOutputStream writes basic data types and graphics of Java objects to OutputStream. ObjectInputStream can be used to read (refactor) objects. Persistent storage of objects can be achieved by using files in streams.

Note: Objects that support the java.io.Serializable interface can only be written to the stream

 

 

 

Code demonstration:

public class ObjectStreamDemo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        /*
         * Store an object on a device that persists (hard disk).
         */
        writeObj();//Object serialization.
    }
    public static void writeObj() throws IOException {
        //1,Files that explicitly store objects.
        FileOutputStream fos = new FileOutputStream("tempfile\\obj.object");
        //2,Add write object function to operation file object.
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        //3,Called the method to write to the object.
        oos.writeObject(new Person("wangcai",20));
        //Close resources.
        oos.close();
    }
}

Class Person

public class Person implements Serializable {
    private String name;
    private int age;
    public Person() {
        super();
    }
    public Person(String name, int age) {
        super();
        this.name = name;
        this.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;
    }
    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }
}

2.2 Object Deserialization Flow ObjectInputStream

ObjectInputStream deserializes the basic data and objects previously written using ObjectOutputStream. Objects that support the java.io.Serializable interface can be read from the stream.

 

 

 

 

Code demo

 

public class ObjectStreamDemo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        readObj();//Deserialization of objects.
    }
    public static void readObj() throws IOException, ClassNotFoundException {
        
        //1,Defining stream object associations stores object files.
        FileInputStream fis = new FileInputStream("tempfile\\obj.object");
        
        //2,Create functional objects for reading objects.
        ObjectInputStream ois = new ObjectInputStream(fis);
        
        Person obj = (Person)ois.readObject();
        
        System.out.println(obj.toString());
        
    }
}

2.3 Serialization Interface

When an object is to be serialized, the class to which the object belongs must implement the Serializable interface. Otherwise, an exception NotSerializableException will occur.

At the same time, when the object is deserialized, if the class file to which the object belongs is modified after serialization, the exception InvalidClassException will also occur when the object is deserialized. The reasons for this anomaly are as follows:

The serial version number of this class does not match the version number of the class descriptor read from the stream.

This class contains unknown data types

There is no accessible parametric construction method for this class

Serializable tag interface. The interface provides a serial version number for classes that need to be serialized. Serial Version UID. The purpose of this version number is to verify whether the serialized objects and corresponding classes match versions.

 

The code is modified as follows. After the modification, the object is written again and the object test is read.

public class Person implements Serializable {
    //Declare a serial version number to the class display.
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;
    public Person() {
        super();
        
    }
    public Person(String name, int age) {
        super();
        this.name = name;
        this.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;
    }
    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }
}

2.4 Transient keyword transient

When an object of a class needs to be serialized, some attributes do not need to be serialized, and attributes that do not need to be serialized can be modified with keyword transients. As long as it is transiently modified, this property will not be serialized when serialized.

At the same time, static modification will not be serialized, because serialization is the persistent storage of object data, while static data belonging to class loading will not be serialized.

The code is modified as follows. After the modification, the object is written again and the object test is read.

public class Person implements Serializable {
    /*
     * Declare a serial version number to the class display.
     */
    private static final long serialVersionUID = 1L;
    private static String name;
    private transient/*transient*/ int age;
    
    public Person() {
        super();
        
    }
    
    public Person(String name, int age) {
        super();
        this.name = name;
        this.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;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }
}

3. Print stream

3.1 Overview of print streams

Print streams add the function of output data to enable them to easily print various data value representations.

Print streams are classified according to streams:

Byte print stream PrintStream

Character Print Writer

Method:

void print(String str): Output any type of data.

void println(String str): Output any type of data, automatically write to the newline operation

Code demonstration:

/* 
 * Requirement: Write the specified data to the printFile.txt file
 * 
 * Analysis:
 *     1,Create stream
 *     2,Writing data
 *     3,Closed flow
 */
public class PrintWriterDemo {
    public static void main(String[] args) throws IOException {
        //Create stream
        //PrintWriter out = new PrintWriter(new FileWriter("printFile.txt"));
        PrintWriter out = new PrintWriter("printFile.txt");
        //2,Writing data
        for (int i=0; i<5; i++) {
            out.println("helloWorld");
        }
        //3,Closed flow
        out.close();
    }
}

3.2 Print stream completes automatic data refresh

The automatic refresh function of file data can be accomplished by constructing method.

Construction method:

Open File Auto Refresh Write Function

  public PrintWriter(OutputStream out, boolean autoFlush)

  public PrintWriter(Writer out, boolean autoFlush)

Code demonstration:

/* 
 * Analysis:
 *     1,Create stream
 *     2,Writing data
 */
public class PrintWriterDemo2 {
    public static void main(String[] args) throws IOException {
        //Create stream
        PrintWriter out = new PrintWriter(new FileWriter("printFile.txt"), true);
        //2,Writing data
        for (int i=0; i<5; i++) {
            out.println("helloWorld");
        }
        //3,Closed flow
        out.close();
    }
}

4. commons-IO

4.1 Import classpath

class files in third-party jar packages added to classpath can only be used in projects

Create lib folders

Copy commons-io.jar to the lib folder

Right-click commons-io.jar, Build Path Add to Build Path

4.2 FilenameUtils

This tool class is used to handle file names, and it can easily solve the problem of different operating system file name specifications.

Common methods:

getExtension(String path): Get the extension of the file;

getName(): Get the file name;

isExtension(String fileName,String ext): Determine whether fileName is an ext suffix name;

4.3 FileUtils

Provides methods for file operations (moving files, reading files, checking whether files exist, etc.).

Common methods:

readFileToString(File file): Read the contents of the file and return a String;

writeStringToFile(File file, String content): Write content into the file;

Copy Directory To Directory (File srcDir, File destDir); folder replication

copyFile(File srcFile,File destFile); folder replication

Code demonstration:

/*
 * Complete the copy of the file
 */
public class CommonsIODemo01 {
    public static void main(String[] args) throws IOException {
        //method1("D:\\test.avi", "D:\\copy.avi");
        
        //adopt Commons-IO Completed the function of file copy.
        FileUtils.copyFile(new File("D:\\test.avi"), new File("D:\\copy.avi"));
    }

    //File duplication
    private static void method1(String src, String dest) throws IOException {
        //1,specify data source 
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));
        //2,Designated destination
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
        //3,read
        byte[] buffer = new byte[1024];
        int len = -1;
        while ( (len = in.read(buffer)) != -1) {
            //4,write
            out.write(buffer, 0, len);
        }
        //5,Closed flow
        in.close();
        out.close();
    }
}

/*
 * Complete duplication of files and folders
 */
public class CommonsIODemo02 {
    public static void main(String[] args) throws IOException {
        //adopt Commons-IO Completed the function of file copy.
        FileUtils.copyFile(new File("D:\\test.avi"), new File("D:\\copy.avi"));
        
        //adopt Commons-IO Completed folder replication function
        //D:\Basic class copy to C:\\abc Under folder
        FileUtils.copyDirectoryToDirectory(new File("D:\\Basic class"), new File("C:\\abc"));
    }
}

Posted by Dracolas on Fri, 11 Oct 2019 02:49:27 -0700