1 transformation flows
1.1 Character streams and two classes related to encoding and decoding problems
-
InputStreamReader: a bridge from a stream of bytes to a stream of characters, whose 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, can be explicitly specified, or can accept the platform’s default character set
-
OutputStreamWriter: a bridge from a character stream to a byte stream, whose parent class is Writer
A bridge from a character stream to a byte stream, encoding written characters as bytes using the specified encoding
The character set it uses can be specified by name, can be explicitly specified, or can accept the platform’s default character set
1.2 Converting streams to read and write data
-
A constructor
The method name instructions InputStreamReader(InputStream in) Create an InputStreamReader object using the default character encoding InputStreamReader(InputStream in,String chatset) Creates an InputStreamReader object with the specified character encoding OutputStreamWriter(OutputStream out) Create an OutputStreamWriter object using the default character encoding OutputStreamWriter(OutputStream out,String charset) Creates an OutputStreamWriter object with the specified character encoding -
Code demo
public class ConversionStreamDemo { public static void main(String[] args) throws IOException { //OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("myCharStream\\osw.txt")); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("myCharStream\\osw.txt"),"GBK"); osw.write("China"); osw.close(); //InputStreamReader isr = new InputStreamReader(new FileInputStream("myCharStream\\osw.txt")); InputStreamReader isr = new InputStreamReader(new FileInputStream("myCharStream\\osw.txt"),"GBK"); // Read data one character at a time int ch; while((ch=isr.read())! = -1) { System.out.print((char)ch); } isr.close(); }}Copy the code
2 Object operation flow
2.1 Object serialization stream
-
Introduction to Object Serialization
- Object serialization: Saving an object to disk or transferring it over the network
- This mechanism represents an object using a sequence of bytes that contains information about the object’s type, its data, and properties stored in the object
- When a byte sequence is written to a file, the file persists information about an object
- Conversely, the byte sequence can be read back from the file, refactor the object, and deserialize it
-
Object serialization stream: ObjectOutputStream
- Writes the raw data type and graph of a Java object to an OutputStream. Objects can be read (refactored) using ObjectInputStream. Persistent storage of objects can be achieved by using stream files. If the stream is a network socket stream, the object can be refactored on another host or in another process
-
A constructor
The method name instructions ObjectOutputStream(OutputStream out) Creates an ObjectOutputStream that writes the specified OutputStream -
Methods for serializing objects
The method name instructions void writeObject(Object obj) Writes the specified object to an ObjectOutputStream -
The sample code
Students in class
public class Student implements Serializable { private String name; private int age; public Student(a) {}public Student(String name, int age) { this.name = name; this.age = age; } public String getName(a) { return name; } public void setName(String name) { this.name = name; } public int getAge(a) { return age; } public void setAge(int age) { this.age = age; } @Override public String toString(a) { return "Student{" + "name='" + name + '\' ' + ", age=" + age + '} '; }}Copy the code
The test class
public class ObjectOutputStreamDemo { public static void main(String[] args) throws IOException { //ObjectOutputStream(OutputStream out) : Creates an ObjectOutputStream that writes the specified OutputStream ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("myOtherStream\\oos.txt")); // Create an object Student s = new Student("Tong Liya".30); //void writeObject(Object obj) : Writes the specified Object to the ObjectOutputStream oos.writeObject(s); // Release resourcesoos.close(); }}Copy the code
-
Matters needing attention
- For an object to be serialized, the class to which the object belongs must implement the Serializable interface
- Serializable is a tag interface that can be implemented without overriding any methods
2.2 Object deserialization stream
-
Object deserialization stream: ObjectInputStream
- ObjectInputStream deserializes raw data and objects previously written with ObjectOutputStream
-
A constructor
The method name instructions ObjectInputStream(InputStream in) Creates an ObjectInputStream that reads from the specified InputStream -
Method to deserialize an object
The method name instructions Object readObject() Read an object from ObjectInputStream -
The sample code
public class ObjectInputStreamDemo { public static void main(String[] args) throws IOException, ClassNotFoundException { //ObjectInputStream(InputStream in) : Creates an ObjectInputStream read from the specified InputStream ObjectInputStream ois = new ObjectInputStream(new FileInputStream("myOtherStream\\oos.txt")); //Object readObject() : Reads an Object from ObjectInputStream Object obj = ois.readObject(); Student s = (Student) obj; System.out.println(s.getName() + ","+ s.getAge()); ois.close(); }}Copy the code
2.3 serialVersionUID&transient
-
serialVersionUID
- After serializing an object with the object serialization stream, if we change the class file that the object belongs to, will we have a problem reading the data?
- An InvalidClassException is thrown
- If something goes wrong, how do you fix it?
- reserialization
- Add a serialVersionUID to the class to which the object belongs
- private static final long serialVersionUID = 42L;
- After serializing an object with the object serialization stream, if we change the class file that the object belongs to, will we have a problem reading the data?
-
transient
- What if the value of a member variable in an object does not want to be serialized?
- Add the transient keyword to the member variable, which does not participate in the serialization process
- What if the value of a member variable in an object does not want to be serialized?
-
The sample code
Students in class
public class Student implements Serializable { private static final long serialVersionUID = 42L; private String name; // private int age; private transient int age; public Student(a) {}public Student(String name, int age) { this.name = name; this.age = age; } public String getName(a) { return name; } public void setName(String name) { this.name = name; } public int getAge(a) { return age; } public void setAge(int age) { this.age = age; } // @Override // public String toString() { // return "Student{" + // "name='" + name + '\'' + // ", age=" + age + / / '} '; / /} } Copy the code
The test class
public class ObjectStreamDemo { public static void main(String[] args) throws IOException, ClassNotFoundException { // write(); read(); } // deserialize private static void read(a) throws IOException, ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("myOtherStream\\oos.txt")); Object obj = ois.readObject(); Student s = (Student) obj; System.out.println(s.getName() + "," + s.getAge()); ois.close(); } / / the serialization private static void write(a) throws IOException { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("myOtherStream\\oos.txt")); Student s = new Student("Tong Liya".30); oos.writeObject(s); oos.close(); }}Copy the code
2.4 Object operation flow exercises
-
Case needs
Create multiple student-class objects to write to a file and read into memory again
-
Implementation steps
- Create a serialized stream object
- Create multiple student objects
- Adds the student object to the collection
- Serialize the collection object to a file
- Create a deserialized stream object
- Read object data from file into memory
-
Code implementation
Students in class
public class Student implements Serializable{ private static final long serialVersionUID = 2L; private String name; private int age; public Student(a) {}public Student(String name, int age) { this.name = name; this.age = age; } public String getName(a) { return name; } public void setName(String name) { this.name = name; } public int getAge(a) { return age; } public void setAge(int age) { this.age = age; }}Copy the code
The test class
public class Demo03 { /** * readLine(): * readLine(): * readObject(): * If there are multiple objects to serialize, it is not recommended to serialize multiple objects to a file, because deserialization is prone to exceptions */ Suggestion: Store multiple objects to be serialized in a collection, and then serialize the collection to a file */ public static void main(String[] args) throws Exception { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("myCode\\oos.txt")); ArrayList
arrayList = new ArrayList<>(); Student s = new Student(" tongliya ",30); Student s01 = new Student(" s01 ",30); //3. Add the student object to the collection arrayList.add(s); arrayList.add(s01); //4. Serialize oos. WriteObject (arrayList); oos.close(); * / // deserialize //5. Create a deserialized stream object ObjectInputStream ois = new ObjectInputStream(new FileInputStream("myCode\\oos.txt")); //6. Read the object data in the file to the memory Object obj = ois.readObject(); ArrayList<Student> arrayList = (ArrayList<Student>)obj; ois.close(); for (Student s : arrayList) { System.out.println(s.getName() + ","+ s.getAge()); }}}Copy the code
3 the Properties collection
3.1 Properties Use as a Map collection
-
Introduce the Properties
- Is a collection class of the Map architecture
- Properties can be saved to or loaded from a stream
- Each key in the property list and its corresponding value is a string
-
Properties Basic usage
public class PropertiesDemo01 { public static void main(String[] args) { // Create a collection object // Properties
prop = new Properties ,string> Properties prop = new Properties(); // Store elements prop.setProperty("test001"."Tong Liya"); prop.setProperty("test002"."Zhao Liying"); prop.setProperty("test003"."Liu Shishi"); // iterate over the collection Set<Object> keySet = prop.keySet(); for (Object key : keySet) { Object value = prop.get(key); System.out.println(key + ","+ value); }}}Copy the code(); / / error ,string>
3.2 Properties as a unique method for Map collections
-
Specific methods
The method name instructions Object setProperty(String key, String value) Set the key and value of the collection, both of type String, using the underlying Hashtable method put String getProperty(String key) Search for properties using the key specified in this property list Set stringPropertyNames() Returns an unmodifiable set of keys from this property list, where keys and their corresponding values are strings -
The sample code
public class PropertiesDemo02 { public static void main(String[] args) { // Create a collection object Properties prop = new Properties(); //Object setProperty(String Key, String Value) : Sets the key and value of the collection, both of type String prop.setProperty("test001"."Tong Liya"); prop.setProperty("test002"."Zhao Liying"); prop.setProperty("test003"."Liu Shishi"); //String getProperty(String key) : Searches for properties using the key specified in this property list // System.out.println(prop.getProperty("itheima001")); // System.out.println(prop.getProperty("itheima0011")); // System.out.println(prop); //Set
stringPropertyNames() : Returns an unmodifiable Set of keys from this property list, where keys and their corresponding values are strings Set<String> names = prop.stringPropertyNames(); for (String key : names) { // System.out.println(key); String value = prop.getProperty(key); System.out.println(key + ","+ value); }}}Copy the code
3.3 Properties and IO stream combined methods
-
And the IO stream method
The method name instructions void load(Reader reader) Read property lists (key and element pairs) from the input character stream void store(Writer writer, String comments) Write this property list (key and element pairs) to the Properties table, writing the output character stream in a format suitable for using the Load (Reader) method -
The sample code
public class PropertiesDemo03 { public static void main(String[] args) throws IOException { // Save the data in the collection to a file // myStore(); // Load the data from the file into the collection myLoad(); } private static void myLoad(a) throws IOException { Properties prop = new Properties(); / / void load (Reader Reader) : FileReader fr = new FileReader("myOtherStream\\fw.txt"); prop.load(fr); fr.close(); System.out.println(prop); } private static void myStore(a) throws IOException { Properties prop = new Properties(); prop.setProperty("test001"."Tong Liya"); prop.setProperty("test002"."Zhao Liying"); prop.setProperty("test003"."Liu Shishi"); //void store(Writer Writer, String comments) : FileWriter fw = new FileWriter("myOtherStream\\fw.txt"); prop.store(fw,null); fw.close(); }}Copy the code
3.4 Properties Collection exercise
-
Case needs
Manually write the name and age in the Properties file, read into the collection, encapsulate the data as a student object, and write it to a local file
-
Implementation steps
- Create the Properties collection to load data from local files into the collection
- Retrieves key-value pair data from the collection and encapsulates it in the student object
- Create a serialized flow object to serialize the student object to a local file
-
Code implementation
Students in class
public class Student implements Serializable { private static final long serialVersionUID = 1L; private String name; private int age; public Student(a) {}public Student(String name, int age) { this.name = name; this.age = age; } public String getName(a) { return name; } public void setName(String name) { this.name = name; } public int getAge(a) { return age; } public void setAge(int age) { this.age = age; } @Override public String toString(a) { return "Student{" + "name='" + name + '\' ' + ", age=" + age + '} '; }}Copy the code
The test class
public class Test { public static void main(String[] args) throws IOException { //1. Create the Properties collection and load the data from the local file into the collection Properties prop = new Properties(); FileReader fr = new FileReader("prop.properties"); prop.load(fr); fr.close(); //2. Get the key-value pair data from the collection and encapsulate it into the student object String name = prop.getProperty("name"); int age = Integer.parseInt(prop.getProperty("age")); Student s = new Student(name,age); //3. Create a serialized stream object to serialize the student object to a local file ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("a.txt")); oos.writeObject(s); oos.close(); }}Copy the code