1. Character stream
1.1 Why does a character stream appear [Understanding]
- Introduction to character streams Since it is not particularly convenient to operate Chinese with byte streams, Java provides character streams Character stream = byte stream + code table
- Chinese byte storage method When copying a text file with a byte stream, the text file will also have Chinese, but there is no problem. The reason is that the underlying operation will automatically perform byte splicing into Chinese. How to identify it as Chinese? When Chinese characters are stored, no matter which encoding is selected for storage, the first byte is a negative number
1.2 Coding table [understanding]
- What is a character set It is a collection of all characters supported by the system, including national characters, punctuation marks, graphic symbols, numbers, etc. l To accurately store and recognize various character set symbols, a computer needs character encoding. A character set must have at least one set of character encoding. Common character sets include ASCII character set, GBXXX character set, Unicode character set, etc.
- common character set
- ASCII character set: lASCII: It is a computer coding system based on the Latin alphabet, used to display modern English, mainly including control characters (enter key, backspace, line feed key, etc.) and displayable characters (English uppercase and lowercase characters, Arabic numerals and Western characters symbol) The basic ASCII character set uses 7 bits to represent a character, with a total of 128 characters. The ASCII extended character set uses 8 bits to represent a character, with a total of 256 characters, which is convenient for supporting common European characters. It is a collection of all characters supported by the system, including national characters, punctuation marks, graphic symbols, numbers, etc.
- GBXXX character set: GBK: The most commonly used Chinese code table. It is an extended specification based on the GB2312 standard. It uses a double-byte encoding scheme and contains a total of 21,003 Chinese characters. It is fully compatible with the GB2312 standard and supports traditional Chinese characters, Japanese and Korean Chinese characters, etc.
- Unicode character set: UTF-8 encoding: It can be used to represent any character in the Unicode standard. It is the preferred encoding for e-mail, web pages, and other applications that store or transmit text. The Internet Engineering Task Force (IETF) requires that all Internet protocols must support UTF-8 encoding. It uses one to four bytes to encode each character encoding rules: 128 US-ASCII characters, encoded in only one byte Latin and other characters need two byte encoding Most commonly used characters (including Chinese), use three-byte encoding Other rarely used Unicode auxiliary characters, using four-byte encoding
1.3 Encoding and decoding problems in strings [application]
related methods
method name | illustrate |
---|---|
byte[] getBytes() | Encodes this String as a sequence of bytes using the platform's default charset |
byte[] getBytes(String charsetName) | encodes this String as a sequence of bytes using the specified charset |
String(byte[] bytes) | Decodes the specified byte array using the platform's default charset to create a string |
String(byte[] bytes, String charsetName) | Creates a string by decoding the specified byte array with the specified charset |
code demo
copypublic class StringDemo { public static void main(String[] args) throws UnsupportedEncodingException { //define a string String s = "China"; //byte[] bys = s.getBytes(); //[-28, -72, -83, -27, -101, -67] //byte[] bys = s.getBytes("UTF-8"); //[-28, -72, -83, -27, -101, -67] byte[] bys = s.getBytes("GBK"); //[-42, -48, -71, -6] System.out.println(Arrays.toString(bys)); //String ss = new String(bys); //String ss = new String(bys,"UTF-8"); String ss = new String(bys,"GBK"); System.out.println(ss); } }
1.4 Character Stream Write Data [Application]
introduce
Writer: abstract parent class for writing character streams
FileWriter: Common subclass for writing character streams
Construction method
method name | illustrate |
---|---|
FileWriter(File file) | Constructs a FileWriter object from the given File object |
FileWriter(File file, boolean append) | Constructs a FileWriter object from the given File object |
FileWriter(String fileName) | Constructs a FileWriter object from the given filename |
FileWriter(String fileName, boolean append) | Constructs a FileWriter object from the given filename and a boolean indicating whether to append data to be written |
member method
method name | illustrate |
---|---|
void write(int c) | write a character |
void write(char[] cbuf) | write a character array |
void write(char[] cbuf, int off, int len) | write part of character array |
void write(String str) | write a string |
void write(String str, int off, int len) | write part of a string |
Refresh and close methods
method name | illustrate |
---|---|
flush() | Refresh the stream, and then continue to write data |
close() | Close the stream, freeing resources, but flushing the stream before closing. Once closed, data can no longer be written |
code demo
copypublic class OutputStreamWriterDemo { public static void main(String[] args) throws IOException { FileWriter fw = new FileWriter("myCharStream\\a.txt"); //void write(int c): write a character // fw.write(97); // fw.write(98); // fw.write(99); //void write(char[] cbuf): write a character array char[] chs = {'a', 'b', 'c', 'd', 'e'}; // fw.write(chs); //void write(char[] cbuf, int off, int len): write part of the character array // fw.write(chs, 0, chs.length); // fw.write(chs, 1, 3); //void write(String str): write a string // fw.write("abcde"); //void write(String str, int off, int len): write part of a string // fw.write("abcde", 0, "abcde".length()); fw.write("abcde", 1, 3); //release resources fw.close(); } }
1.5 Character stream reading data [Application]
- introduce Reader: abstract parent class for reading character streams FileReader: A common subclass for reading character streams
- Construction method Method Name Description FileReader(File file) Creates a new FileReader given a File to read data from FileReader(String fileName) Creates a new FileReader given a file name to read data from
member method
method name | illustrate |
---|---|
int read() | Read character data one at a time |
int read(char[] cbuf) | Read character array data one at a time |
code demo
copypublic class InputStreamReaderDemo { public static void main(String[] args) throws IOException { FileReader fr = new FileReader("myCharStream\\b.txt"); //int read(): read one character data at a time // int ch; // while ((ch=fr.read())!=-1) { // System.out.print((char)ch); // } //int read(char[] cbuf): read one character array data at a time char[] chs = new char[1024]; int len; while ((len = fr.read(chs)) != -1) { System.out.print(new String(chs, 0, len)); } //release resources fr.close(); } }
1.6 Character stream user registration case [Application]
case requirements
Save the user name and password entered by the keyboard to the local for permanent storage
Implementation steps
- Get the username and password entered by the user
- Write the username and password entered by the user to a local file
- Shutdown, release resources
Code
copypublic class CharStreamDemo8 { public static void main(String[] args) throws IOException { //Requirement: Save the user name and password entered by the keyboard to the local for permanent storage //Requirements: The username is on one line alone, and the password is on one line alone //analyze: //1. Realize keyboard entry, enter user name and password Scanner sc = new Scanner(System.in); System.out.println("Please enter username"); String username = sc.next(); System.out.println("Please enter password"); String password = sc.next(); //2. Write the user name and password to the local file respectively. FileWriter fw = new FileWriter("charstream\\a.txt"); //Write username and password to a file fw.write(username); //Indicates writing a carriage return and line feed windows \r\n MacOS \r Linux \n fw.write("\r\n"); fw.write(password); //refresh stream fw.flush(); //3. Shutdown, release resources fw.close(); } }
1.7 Character buffer stream [Application]
Introduction to Character Buffer Streams
- BufferedWriter: Writes text to a character output stream, buffering characters to provide efficient writing of single characters, arrays, and strings, the buffer size can be specified, or the default size can be accepted. The default is large enough for most purposes
- BufferedReader: Reads text from a character input stream, buffering characters to provide efficient reading of characters, arrays, and lines, the buffer size can be specified, or the default size can be used. The default is large enough for most purposes
Construction method
method name | illustrate |
---|---|
BufferedWriter(Writer out) | Create a character buffered output stream object |
BufferedReader(Reader in) | Create a character buffered input stream object |
code demo
copypublic class BufferedStreamDemo01 { public static void main(String[] args) throws IOException { //BufferedWriter(Writer out) BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\bw.txt")); bw.write("hello\r\n"); bw.write("world\r\n"); bw.close(); //BufferedReader(Reader in) BufferedReader br = new BufferedReader(new FileReader("myCharStream\\bw.txt")); //Read character data one at a time // int ch; // while ((ch=br.read())!=-1) { // System.out.print((char)ch); // } //Read character array data one at a time char[] chs = new char[1024]; int len; while ((len=br.read(chs))!=-1) { System.out.print(new String(chs,0,len)); } br.close(); } }
1.8 Unique functions of character buffer stream [Application]
method introduction
BufferedWriter:
method name | illustrate |
---|---|
void newLine() | Write a line with the line separator, the line separator string is defined by the system property |
BufferedReader:
method name | illustrate |
---|---|
String readLine() | Read a line of text. result A string containing the contents of the line, excluding any line termination characters, or null if the end of the stream has been reached |
code demo
copypublic class BufferedStreamDemo02 { public static void main(String[] args) throws IOException { //Create a character buffered output stream BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\bw.txt")); //write data for (int i = 0; i < 10; i++) { bw.write("hello" + i); //bw.write("\r\n"); bw.newLine(); bw.flush(); } //release resources bw.close(); //Create a character buffered input stream BufferedReader br = new BufferedReader(new FileReader("myCharStream\\bw.txt")); String line; while ((line=br.readLine())!=null) { System.out.println(line); } br.close(); } }
1.9 Case of data sorting in character buffer stream operation file [Application]
case requirements
Use the character buffer stream to read the data in the file, and write to the local file again after sorting
Implementation steps
- Read the data from the file into the program
- Process the read data
- Add the processed data to the collection
- Sort the data in the collection
- Write the data in the sorted collection to a file
Code
copypublic class CharStreamDemo14 { public static void main(String[] args) throws IOException { //Requirement: read the data in the file, write to the local file again after sorting //analyze: //1. To read the data in the file. BufferedReader br = new BufferedReader(new FileReader("charstream\\sort.txt")); //The output stream must not be written here, because the contents of the file will be emptied //BufferedWriter bw = new BufferedWriter(new FileWriter("charstream\\sort.txt")); String line = br.readLine(); System.out.println("The read data is" + line); br.close(); //2. Cut according to the space String[] split = line.split(" ");//9 1 2 5 3 10 4 6 7 8 //3. Change the array of string type into int type int [] arr = new int[split.length]; //Traversing the split array can perform type conversion. for (int i = 0; i < split.length; i++) { String smallStr = split[i]; //type conversion int number = Integer.parseInt(smallStr); //Store the converted result in arr arr[i] = number; } //4. Sort Arrays.sort(arr); System.out.println(Arrays.toString(arr)); //5. Write the sorted results back to the local 1 2 3 4... BufferedWriter bw = new BufferedWriter(new FileWriter("charstream\\sort.txt")); //write out for (int i = 0; i < arr.length; i++) { bw.write(arr[i] + " "); bw.flush(); } //release resources bw.close(); } }
2. Conversion stream
2.1 Two classes related to encoding and decoding problems in character stream [Understanding]
- InputStreamReader: 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, can be specified explicitly, or can accept the platform's default character set
- OutputStreamWriter: It is a bridge from character stream to byte stream, the parent class is Writer is a bridge from a character stream to a byte stream, using the specified encoding to encode the written characters into bytes The character set it uses can be specified by name, can be specified explicitly, or can accept the platform's default character set
2.2 Conversion stream read and write data [Application]
Construction method
method name | illustrate |
---|---|
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) | Create an OutputStreamWriter object using the default character encoding |
OutputStreamWriter(OutputStream out,String charset) | Creates an OutputStreamWriter object using the specified character encoding |
code demo
copypublic 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 character data one at a time int ch; while ((ch=isr.read())!=-1) { System.out.print((char)ch); } isr.close(); } }
3. Object operation flow
3.1 Object Serialization Stream [Application]
Introduction to Object Serialization
- Object serialization: saving objects to disk or transferring objects over the network
- This mechanism is to use a sequence of bytes to represent an object, which contains information such as the type of the object, the data of the object, and the attributes stored in the object.
- After the byte sequence is written to the file, it is equivalent to persistently saving the information of an object in the file
- Conversely, the byte sequence can also be read back from the file, reconstruct the object, and deserialize it
Object serialization stream: ObjectOutputStream
- Write primitive data types and graphics of Java objects to an OutputStream. Objects can be read (reconstructed) using ObjectInputStream. Persistent storage of objects can be achieved through files using streams. If the stream is a network socket stream, the object can be reconstructed on another host or in another process
Construction method
method name | illustrate |
---|---|
ObjectOutputStream(OutputStream out) | Creates an ObjectOutputStream that writes to the specified OutputStream |
Methods for serializing objects
method name | illustrate |
---|---|
void writeObject(Object obj) | Writes the specified object to the ObjectOutputStream |
sample code
student class
copypublic class Student implements Serializable { private String name; private int age; public Student() { } public Student(String name, int age) { 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 "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
test class
copypublic class ObjectOutputStreamDemo { public static void main(String[] args) throws IOException { //ObjectOutputStream(OutputStream out): Creates an ObjectOutputStream written to the specified OutputStream ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("myOtherStream\\oos.txt")); //create object Student s = new Student("Tong Liya",30); //void writeObject(Object obj): write the specified object to ObjectOutputStream oos.writeObject(s); //release resources oos.close(); } }
Precautions
- For an object to be serialized, the class to which the object belongs must implement the Serializable interface
- Serializable is a marker interface that implements this interface without rewriting any methods
3.2 Object deserialization flow [Application]
Object deserialization stream: ObjectInputStream
- ObjectInputStream deserializes raw data and objects previously written using ObjectOutputStream
Construction method
method name | illustrate |
---|---|
ObjectInputStream(InputStream in) | Creates an ObjectInputStream that reads from the specified InputStream |
Methods to deserialize objects
method name | illustrate |
---|---|
Object readObject() | Read an object from ObjectInputStream |
sample code
copypublic class ObjectInputStreamDemo { public static void main(String[] args) throws IOException, ClassNotFoundException { //ObjectInputStream(InputStream in): Creates an ObjectInputStream that reads from the specified InputStream ObjectInputStream ois = new ObjectInputStream(new FileInputStream("myOtherStream\\oos.txt")); //Object readObject(): read an object from ObjectInputStream Object obj = ois.readObject(); Student s = (Student) obj; System.out.println(s.getName() + "," + s.getAge()); ois.close(); } }
3.3serialVersionUID&transient[Application]
serialVersionUID
- After serializing an object with the object serialization stream, if we modify the class file to which the object belongs, will there be any problems reading the data?
- There will be problems, and an InvalidClassException will be thrown
- If something goes wrong, how to solve it?
- re-serialize
- Add a serialVersionUID to the class to which the object belongs
- private static final long serialVersionUID = 42L;
transient
- If the value of a member variable in an object does not want to be serialized, how to achieve it?
- Add the transient keyword to the member variable, and the member variable marked by this keyword does not participate in the serialization process
sample code
student class
copypublic class Student implements Serializable { private static final long serialVersionUID = 42L; private String name; // private int age; private transient int age; public Student() { } public Student(String name, int age) { 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 "Student{" + // "name='" + name + '\'' + // ", age=" + age + // '}'; // } }
test class
copypublic class ObjectStreamDemo { public static void main(String[] args) throws IOException, ClassNotFoundException { // write(); read(); } //deserialization private static void read() 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(); } //Serialization private static void write() throws IOException { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("myOtherStream\\oos.txt")); Student s = new Student("Tong Liya", 30); oos.writeObject(s); oos.close(); } }
3.4 Object Operation Flow Exercise [Application]
case requirements
Create multiple student class objects, write them to the file, and read them into memory again
Implementation steps
- Create a serialized stream object
- Create multiple student objects
- Add the student object to the collection
- Serialize the collection object to a file
- Create a deserialized stream object
- Read the object data in the file into memory
Code
student class
copypublic class Student implements Serializable{ private static final long serialVersionUID = 2L; private String name; private int age; public Student() { } public Student(String name, int age) { 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; } }
test class
copypublic class Demo03 { /** * read(): * Read to the end of the file and the return value is -1 * readLine(): * Read to the end of the file and return the value null * readObject(): * Read to the end of the file and throw an exception directly * If there are multiple objects to be serialized, it is not recommended to serialize multiple objects directly into the file, because it is easy to get an exception when deserializing * Suggestion: Store multiple objects to be serialized into a collection, then serialize the collection into a file */ public static void main(String[] args) throws Exception { /*// Serialization //1.Create a serialized stream object ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("myCode\\oos.txt")); ArrayList<Student> arrayList = new ArrayList<>(); //2.Create multiple student objects Student s = new Student("Tong Liya",30); Student s01 = new Student("Tong Liya",30); //3.Add the student object to the collection arrayList.add(s); arrayList.add(s01); //4.Serialize the collection object to a file oos.writeObject(arrayList); oos.close();*/ // deserialization //5. Create a deserialized stream object ObjectInputStream ois = new ObjectInputStream(new FileInputStream("myCode\\oos.txt")); //6. Read the object data in the file into 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()); } } }
4.Properties collection
4.1 The use of Properties as a Map collection [Application]
Introduction to Properties
- It is a collection class of Map system
- Properties can be saved to or loaded from streams
- Each key and its corresponding value in the property list is a string
Basic use of Properties
copypublic class PropertiesDemo01 { public static void main(String[] args) { //Create a collection object // Properties<String,String> prop = new Properties<String,String>(); //Error Properties prop = new Properties(); //storage element prop.put("itheima001", "Tong Liya"); prop.put("itheima002", "Zhao Liying"); prop.put("itheima003", "Liu Shishi"); //iterate through the collection Set<Object> keySet = prop.keySet(); for (Object key : keySet) { Object value = prop.get(key); System.out.println(key + "," + value); } } }
4.2Properties as a unique method of Map collection [Application]
unique method
method name | illustrate |
---|---|
Object setProperty(String key, String value) | Set the key and value of the collection, both are of String type, and the bottom layer calls the Hashtable method put |
String getProperty(String key) | Searches for properties using the keys specified in this property list |
Set stringPropertyNames() | Returns an unmodifiable set of keys from this property list, where the keys and their corresponding values are strings |
sample code
copypublic class PropertiesDemo02 { public static void main(String[] args) { //Create a collection object Properties prop = new Properties(); //Object setProperty(String key, String value): Set the key and value of the collection, both of String type prop.setProperty("itheima001", "Tong Liya"); prop.setProperty("itheima002", "Zhao Liying"); prop.setProperty("itheima003", "Liu Shishi"); //String getProperty(String key): Searches for a property 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<String> stringPropertyNames(): Returns an unmodifiable set of keys from this property list, where the 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); } } }
4.3 The method of combining Properties and IO stream [Application]
Method combined with IO stream
method name | illustrate |
---|---|
void load(Reader reader) | Reads a property list (key and element pair) from an input character stream |
void store(Writer writer, String comments) | writes this property list (key and element pair) into this Properties table, in a format suitable for use with the load(Reader) method to an output character stream |
sample code
copypublic 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() 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() throws IOException { Properties prop = new Properties(); prop.setProperty("itheima001","Tong Liya"); prop.setProperty("itheima002","Zhao Liying"); prop.setProperty("itheima003","Liu Shishi"); //void store(Writer writer, String comments): FileWriter fw = new FileWriter("myOtherStream\\fw.txt"); prop.store(fw,null); fw.close(); } }
4.4Properties Collection Practice [Application]
case requirements
Manually write the name and age in the Properties file, read it into the collection, encapsulate the data into a student object, and write it to the local file
Implementation steps
- Create a Properties collection and load data from local files into the collection
- Get the key-value pair data in the collection and encapsulate it into the student object
- Create a serialized stream object to serialize the student object into a local file
Code
student class
copypublic class Student implements Serializable { private static final long serialVersionUID = 1L; private String name; private int age; public Student() { } public Student(String name, int age) { 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 "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
test class
copypublic class Test { public static void main(String[] args) throws IOException { //1. Create a Properties collection and load the data in 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 in 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 and serialize the student object into a local file ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("a.txt")); oos.writeObject(s); oos.close(); } }