JAVA Class21

Learning Content:

1.Properties class:

The Properties class inherits from HashTable, so it stores elements in key-value form. A container commonly used to store elements in an IO stream, and can read and write data from the hard disk.

Common method:

store, write data to hard disk

load, read data from hard disk

stringPropertyNames, returns a Set of all keys

setProperty(String,String), add elements

getProperty, get the element

public class Test {
    public static void write() {
        File f = new File("d:\\test\\properties.test");
        Properties p = new Properties();
        p.setProperty("g","stu");
        /*try (FileOutputStream fos = new FileOutputStream(f,true);){
            p.store(fos,"new information");
        } catch (IOException e) {
            e.printStackTrace ();
        }*/
        try (FileWriter fw = new FileWriter(f)){
            p.store(fw, "Add new information" );
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }
    public static void read() {
        File f = new File("d:\\test\\properties.test");
        Properties p = new Properties();
        try (FileInputStream fis = new FileInputStream(f);){
            p.load(fis);
            Set<String> set = p.stringPropertyNames();
            for(Iterator<String> it = set.iterator();it.hasNext();) {
                String key = it.next();
                String value = p.getProperty(key);
                System.out.println(key+":"+value);
            }
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }
}

2. Object stream (object serialization and deserialization)

Read and write the instantiated object, note that the class must use the Serializable (serialization) interface

Why serialize and deserialize objects: For the sake of unification, the data we transmit or the data saved in files need to be serialized and encoded, which is equivalent to a common standard for both parties. According to this According to this standard, regardless of whether there are differences in their respective environments, each can translate correct data that they can understand according to this standard.

(1) The Serializable (serialization) interface is an empty interface with no member variables and no abstract methods. This interface is called a marker interface, and classes using this interface can be serialized

It should be noted that static members cannot be serialized, because static members are loaded with the loading of the class and coexist with the class. If the "serialized" static member variable is read in another JVM, then The static member variable value of the current JVM will be used.

(2) transient modifier: member variables can be prohibited from being serialized.

(3) serialVersionUID: When the modifier is modified, the serial numbers generated automatically before and after do not match, and the serialized object cannot be read. serialVersionUID is used to represent the current version of this class. If there are changes, such as newly designed properties, This version number should be modified to solve the serial number mismatch problem.

import java.io.Serializable;

public  class Hero implements Serializable{ // Empty interface, marker interface 
    private String name;
     // Indicates the current version of this class, if there are changes, such as newly designed properties, the version number should be modified to solve the serial number mismatch Problem 
    private  static  final  long serialVersionUID = 1L ;
     private  int hp; // When modifying the modifier, the serial numbers before and after do not match, and the serialized object cannot be read
     // Static members cannot be serialized because static members It is loaded with the loading of the class,
     // coexists with the class, and static members are default initial values;
     // serialization of member variables is prohibited
     // transient private String sex; 
    public String getName() {
         return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getHp() {
        return hp;
    }
    public void setHp(int hp) {
        this.hp = hp;
    }
    public Hero(String name, int hp) {
        super();
        this.name = name;
        this.hp = hp;
    }
    public Hero() {
        super();
    }
    
}
public class Test {
    public static void writeHero(ArrayList<Hero> herolist) {
        File f = new File("d:\\test\\Dota2.dota");
        try (FileOutputStream fis = new FileOutputStream(f);
              ObjectOutputStream oos = new ObjectOutputStream(fis);
              ){
            oos.writeObject (herolist);
            System.out.println( "Write complete!" );
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }
    public static ArrayList<Hero> readHero() {
        File f = new File("d:\\test\\Dota2.dota");
        ArrayList<Hero> herolist = new ArrayList<Hero>();
        try (FileInputStream fos = new FileInputStream(f);
              ObjectInputStream ois = new ObjectInputStream(fos);
              ){
             herolist = (ArrayList<Hero>)ois.readObject();
             System.out.println( "Read complete!" );
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return herolist;
    }
}

 3.Print flow

PrintStream,PrintWriter

Features: Not responsible for the data source, only responsible for the data purpose, adding functions to other output streams, never throwing IO exceptions.

public class Test5 {
    public static void write() {
    public static void copy() {
        File f = new File("d:\\test\\LOL.txt");
        try ( BufferedReader br = new BufferedReader(new FileReader(f));
                PrintWriter pw = new PrintWriter(new FileWriter("d:\\test\\copy.txt"));
                ){
            String line =null;
            while((line=br.readLine())!=null) {
                pw.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }
    public static void main(String[] args) {
        File f = new File("d:\\test\\print.txt");
        try (PrintStream ps = new PrintStream(f);
                //PrintWriter pw = new PrintWriter(f);
                FileOutputStream fos = new FileOutputStream(f);
                PrintWriter pw = new PrintWriter(fos, true ); // Pass in the stream object, call println, printf, format to automatically flush 
                ){ // Not responsible for the data source, only responsible for the data purpose
             // Add functions to other output streams, never Throw IO exception 
            ps.println("a" );
            ps.println("b");
            pw.println("c");
            pw.println("d");

        } catch (IOException e) {
            e.printStackTrace ();
        }
        int[] i = {1};
        System.out.println(i); // void java.io.PrintStream.println(Object x) print address 
        char [] ch = {'a','b' };
        System.out.println(ch); // void java.io.PrintStream.println(char[] x) print string 
    }
}

 4. common.io package

Provides packaging tools for manipulating files and folders

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

public class Test6 {
    public static void fn() {
        FilenameUtils fnu = new FilenameUtils();
        String name = fnu.getExtension("d:\\test\\LOL.txt"); // Get the extension 
        String fname = fnu.getName("d:\\test\\LOL.lol"); // Get File name 
        boolean flag = fnu.isExtension("d:\\test\\LOL.txt","txt"); // Check file type 
        System.out.println(name+""+fname+""+ flag);
    }
    public static void main(String[] args) throws IOException {
        fn();
        FileUtils fu = new FileUtils();
        System.out.println();
        String s =fu.readFileToString( new File("d:\\test\\LOL.txt"),"UTF-8"); // Read the file content 
        fu.copyDirectory( new File("d:\\study "), new File("d:\\tocopy")); // copy folder 
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324715453&siteId=291194637