day20
Chapter 1 buffer flow
1.1 general
Buffer stream, also known as efficient stream, is an enhancement of four basic FileXxx streams, so it is also four streams, classified according to data type:
- Byte buffer stream: BufferedInputStream, BufferedOutputStream
- Character buffer stream: BufferedReader,BufferedWriter
The basic principle of buffered stream is that when creating stream objects, a built-in buffer array of default size will be created to reduce the number of system IO through buffer reading and writing, so as to improve the efficiency of reading and writing.
1.2 byte buffer stream
Construction method
- public BufferedInputStream(InputStream in): create a new buffered input stream.
- public BufferedOutputStream(OutputStream out): create a new buffered output stream.
import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; /* java.io.BufferedOutputStream extends OutputStream BufferedOutputStream:Byte buffered output stream Common member methods inherited from parent class: - public void close():Close this output stream and free any system resources associated with this stream. - public void flush():Refresh this output stream and force any buffered output bytes to be written out. - public void write(byte[ ] b):Writes the b.length byte from the specified byte array to this output stream. - public void write(byte[ ] b, int off, int len):Write len bytes from the specified byte array and output to this output stream from offset off. - public abstract void write(int b):Outputs the specified bytes to the stream. Construction method: BufferedOutputStream(OutputStream out)Create a new buffered output stream to write data to the specified underlying output stream. BufferedOutputStream(OutputStream out,int size)Creates a new buffered output stream to write data with the specified buffer size to the specified underlying output stream Parameters: OutputStream out:Byte output stream We can pass FileOutputStream. The buffer stream will add a buffer to FileOutputStream to improve the writing efficiency of FileOutputStream int size:Specifies the size of the internal buffer of the buffer stream without specifying the default Use steps (key points) 1.Create a FileOutputStream object and bind the destination to be output in the construction method 2.Create BufferedOutputStream object and pass FileOutputStream object in the construction method to improve the efficiency of FileOutputStream object 3.Use the write method in the BufferedOutputStream object to write the data to the internal buffer 4.Use the method flush in the BufferedOutputStream object to flush the data in the internal buffer into the file 5.Release resources (the flush method will be called to refresh the data first, and step 4 can be omitted) */ public class Demo01BufferedOutputStream { public static void main(String[] args) throws IOException { //1. Create a FileOutputStream object and bind the destination to be output in the construction method FileOutputStream fos = new FileOutputStream("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\a.txt"); //2. Create BufferedOutputStream object and pass FileOutputStream object in the construction method to improve the efficiency of FileOutputStream object BufferedOutputStream bos = new BufferedOutputStream(fos); //3. Use the write method in the BufferedOutputStream object to write the data to the internal buffer bos.write("I write the data to the internal buffer".getBytes()); //4. Use the method flush in the BufferedOutputStream object to flush the data in the internal buffer into the file bos.flush(); //5. Release resources (the flush method will be called to refresh the data first, and step 4 can be omitted) bos.close(); } }
import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; /* java.io.BufferedInputStream extends InputStream BufferedInputStream:Byte buffered input stream Member methods inherited from parent class: int read()Reads the next byte of data from the input stream. int read(byte[] b)A certain number of bytes are read from the input stream and stored in the buffer array b. void close()Close this input stream and release all system resources associated with it. Construction method: BufferedInputStream(InputStream in)Create a BufferedInputStream and save its parameters, the input stream in, for future use. BufferedInputStream(InputStream in,int size)Create a BufferedInputStream with the specified buffer size and save its parameter, the input stream in, for later use. Parameters: InputStream in:Byte input stream We can pass FileInputStream. The buffer stream will add a buffer to FileInputStream to improve the reading efficiency of FileInputStream int size:Specifies the size of the internal buffer of the buffer stream without specifying the default Use steps (key points): 1.Create a FileInputStream object and bind the data source to be read in the construction method 2.Create BufferedInputStream object and pass FileInputStream object in the construction method to improve the reading efficiency of FileInputStream object 3.Use the read method in the BufferedInputStream object to read the file 4 .Release resources */ public class Demo02BufferedInputStream { public static void main(String[] args) throws IOException { //1. Create a FileInputStream object and bind the data source to be read in the construction method FileInputStream fis = new FileInputStream("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\a.txt"); //2. Create BufferedInputStream object and pass FileInputStream object in the construction method to improve the reading efficiency of FileInputStream object BufferedInputStream bis = new BufferedInputStream(fis); //3. Use the read method in BufferedInputStream object to read the file //int read() reads the next byte of data from the input stream. /*int len = 0; while ((len = bis.read()) != -1){ System.out.println(len); }*/ //int read(byte[] b) reads a certain number of bytes from the input stream and stores them in buffer array B. byte[] bytes = new byte[1024]; int len = 0; while ((len = bis.read(bytes))!= -1){ System.out.println(new String(bytes, 0, len)); } //4 . Release resources bis.close(); } }
1.3 character buffer stream
Construction method
- public BufferedReader(Reader in): create a new buffered input stream.
- Public buffered writer (writer out): create a new buffered output stream.
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; /* java.io.BufferedWriter extends writer BufferedWriter:Character buffered output stream Common member methods inherited from parent class: - void write(int c)Write a single character. - void write(char[] cbuf)Write character array. - abstract void write(char[] cbuf,int off,int len)Write a part of the character array, the starting index of the of array, and the number of characters written by len. - void write(String str)Write string. - void write(String str, int off, int len)Write a part of the string, the start index of the off string, and the number of characters written by Len. - void flush()Flush the buffer of the stream. - void close()Close this stream, but refresh it first. Construction method: BufferedWriter(Writer out)Create a buffered character output stream that uses the default size output buffer. BufferedWriter(writer out,int sz)Creates a new buffered character output stream using an output buffer of a given size. Parameters: writer out:Character output stream We can pass the FileWriter, and the buffer stream will add a buffer to the FileWriter to improve the writing efficiency of the FileWriter int sz:Specifies the size of the buffer, not the default size Unique member methods: void newLine() Write a line separator. Different line separators will be obtained according to different operating systems Line break symbol: Windows: \r\n Linux: /n mac: /r Use steps: 1.Create a character buffer output stream object and pass the character output stream in the construction method 2.Call the write method in the character buffer output stream to write the data to the memory buffer 3.Call the method flush in the character buffer output stream to refresh the data in the memory buffer into the file 4.Release resources */ public class Demo03BufferedWriter { public static void main(String[] args) throws IOException { //1. Create a character buffer output stream object and transfer the character output stream in the construction method BufferedWriter bw = new BufferedWriter(new FileWriter("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\b.txt")); //2. Call the write method in the character buffer output stream to write the data into the memory buffer for (int i = 0; i < 10; i++){ bw.write("Intelligence Podcast"); //bw.write("\r\n"); bw.newLine(); } //3. Call the method flush in the character buffer output stream to refresh the data in the memory buffer into the file bw.flush(); //4. Release resources bw.close(); } }
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /* java.io.BufferedReader extends Reader Common member methods inherited from parent class: int read()Read a single character and return. int read(char[] cbuf)Read multiple characters at a time and read the characters into the array. void close()Close the flow and release all resources associated with it. Construction method: BufferedReader(Reader in)Create a buffered character input stream that uses the default size input buffer. BufferedReader(Reader in, int sz)Creates a buffered character input stream using an input buffer of the specified size. Parameters: Reader in :Character input stream We can pass FileReader, and the buffer stream will add a buffer to FileReader to improve the reading efficiency of FileReader Unique member methods: String readline()Read a text line. Read a row of data Line termination symbol: a line can be considered terminated by one of the following characters: line feed ('\ n'), carriage return ('\ r'), or carriage return followed by line feed (\ r\n). Return value: The string containing the content of the line, without any line terminator. If the end of the stream has been reached, null will be returned Use steps: 1.Create a character buffer input stream object and pass the character input stream in the construction method 2.Use the method read/readLine in the character buffered input stream object to read text 3.Release resources */ public class Demo04BufferedReader { public static void main(String[] args) throws IOException { //1. Create a character buffer input stream object and transfer the character input stream in the construction method BufferedReader br = new BufferedReader(new FileReader("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\b.txt")); //2. Use the method read/readLine in the character buffer input stream object to read the text /* int len = 0; char[] bytes = new char[1024]; while ((len = br.read(bytes)) != -1){ System.out.println(new String(bytes, 0, len)); } */ String line; while ((line = br.readLine()) != null){ System.out.println(line); } br.close(); } }
1.4 text sorting
3.Shi Zhong, Shi Lang Guo Youzhi, Fei Yi, Dong Yun and others are all good and honest. They are determined to be loyal and pure. They are based on the simplicity of the former Emperor to leave their majesty. The fool thinks that the things in the words are no big or small. If he learns about them, and then implements them, he will benefit, fill the gaps and be of wide benefit. 8.May your majesty entrust his officials to revive the thief. If it doesn't work, he will punish his officials and Sue the spirit of the former Emperor. If there are no words to promote morality, the slowness of you, Yi and permission will be blamed to show its blame;Your majesty is also advised to seek advice from himself, learn good ways, observe and accept elegant words, and deeply pursue the last edict of the former Emperor. I am very grateful for your kindness. 4.The general Xiang Chong, who was both gentle in nature and gentle in conduct, was well versed in military affairs and tried it in the past. The former Emperor called it Neng, which was supervised by the public's opinion. The fool thinks that if he learns about the affairs in the camp and consults him, he will be able to make the formation harmonious and get the advantages and disadvantages. 2.In the palace and in the government, all are one. It is not appropriate to have similarities and differences. If there are those who commit crimes and are loyal to the good, it is appropriate to pay a punishment reward to the Secretary, so as to show his Majesty's justice. It is not appropriate to be biased and make the internal and external laws different. 1.The first emperor's business was not half started, but the middle road collapsed. Today, Yizhou is weak. This is the autumn of crisis. However, the bodyguard's ministers are unremitting inside, and the loyal people forget to be outside. They cover the special treatment of chasing the former Emperor and want to repay it to their majesty. It is better to open up the holy hearing, to honor the legacy of the former Emperor and the spirit of great people with lofty ideals. It is better not to belittle yourself, quote a word unjustly, and plug the road of loyal admonition. 9.Today, we should stay away, face the table with tears and don't know what to say. 6.The minister is based on cloth clothes. He works hard in Nanyang, lives in troubled times, and reaches the princes without seeking knowledge. The first Emperor didn't treat his ministers as despicable and self defeating. He took care of his ministers in the thatched cottage three times and consulted his ministers on the affairs of the world. Therefore, he was grateful, so he allowed the first emperor to drive away. After the collapse, when he was appointed to the defeated army, Tai was in danger. It's been 20 years. 7.The former Emperor knew that his ministers were cautious, so he sent his ministers to great events in the face of collapse. Since he was ordered, he has been worried and sighed day and night for fear that the entrustment will not work, so as to hurt the Ming of the former Emperor. Therefore, he crossed Lu in May and went deep into no hair. Now the South has been determined, and the soldiers have enough armour. When the award leads the three armies, the north will determine the Central Plains. The common people are exhausted and dull, eliminate the evils, revive the Han Dynasty, and return to the old capital. This minister is therefore loyal to the former Emperor. As for the consideration of profits and losses and making good advice, it is also the responsibility of you, Yi and Yun. 5.Pro virtuous officials, far from villains, this was the first Han Dynasty, so it prospered;Pro villains, far virtuous officials, since then, the Han Dynasty has fallen. When the first emperor was there, he talked about this matter with his ministers, and sighed and hated Yu Huan and Ling. Shi Zhong, Shang Shu, Chang Shi and joining the army. This is a minister who has learned of Zhenliang's death Festival. I hope your majesty can believe it and the prosperity of the Han Dynasty can be expected in a few days.
import java.io.*; import java.util.HashMap; import java.util.Set; /* practice; Sort the contents of the text According to (1,2,3...) Sequential sorting analysis: 1.Create a HashMap collection object, which can: store the sequence number of each line of text (1,2,3,...); Value: stores the text of each line 2.Create a character buffer input stream object and bind the character input stream in the construction method 3.Create a character buffer output stream object and bind the character output stream in the construction method 4.Use the readLine method in the character buffered input stream to read the text line by line 5.Cut the read text to obtain the serial number and text content in the line 6.Store the cut serial number and text content in the HashMap set (the key serial number is ordered and will be automatically sorted 1,2,3,4...) 7.Through the calendar HashMap collection, get each key value pair 8.Splice each key value pair into a text line 9.write the spliced text into the file using the method in the character buffer output stream 10.Release resources */ public class Demo05Test { public static void main(String[] args) throws IOException { //1. Create a HashMap collection object, which can: store the serial number of each line of text (1,2,3,.); Value: stores the text of each line HashMap<String, String> map = new HashMap<>(); //2. Create a character buffer input stream object and bind the character input stream in the construction method BufferedReader br = new BufferedReader(new FileReader("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\sort.txt")); //3. Create a character buffer output stream object and bind the character output stream in the construction method BufferedWriter bw = new BufferedWriter(new FileWriter("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\sort1.txt")); //4. Use the readLine method in the character buffer input stream to read the text line by line String line; while ((line = br.readLine()) != null){ //5. Cut the read text to obtain the serial number and text content in the line String[] arr = line.split("\\."); //6. Store the cut serial number and text content in the HashMap set (the key serial number is ordered and will be automatically sorted 1,2,3,4...) map.put(arr[0], arr[1]); } //7. Through the calendar HashMap set, obtain each key value pair Set<String> set = map.keySet(); for (String key : set){ String value = map.get(key); //8. Splice each key value pair into a text line line = key + "." + value; //9. write the spliced text into the file using the method in the character buffer output stream bw.write(line); bw.newLine(); } //10. Release resources bw.close(); br.close(); } }
Chapter 2 conversion flow
2.1 character encoding and character set
Character encoding
The information stored in the computer is represented by binary numbers, and the numbers, English, punctuation marks, Chinese characters and other characters we see on the screen are the result of binary number conversion. According to certain rules, storing characters in the computer is called encoding. On the contrary, the binary number stored in the computer is parsed and displayed according to some rules, which is called decoding. For example, if it is stored according to rule A and parsed according to rule A, the correct text symbols can be displayed. On the contrary, storing according to rule A and parsing according to rule B will lead to garbled code.
Encoding: character (understandable) – byte (incomprehensible)
Decoding: bytes (unreadable) – > characters (intelligible)
- Character Encoding: a set of correspondence rules between natural language characters and binary numbers.
- Coding table: the corresponding rules between words in life and binary in computer
character set
Charset: also known as encoding table. It is a collection of all characters supported by the system, including national characters, punctuation marks, graphic symbols, numbers, etc.
To accurately store and recognize various character set symbols, the computer needs character coding. A set of character set must have at least one set of character coding. Common character sets include ASCII character set, GBK character set, Unicode character set, etc.
It can be seen that when the encoding is specified, the corresponding character set will be specified naturally, so the encoding is what we should care about ultimately.
- ASCII character set:
- ASCII (American Standard Code for information interchange) is a set of computer coding system based on Latin alphabet, which is 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 symbols).
- The basic ASCII character set, using 7 bits to represent a character, a total of 128 characters. The ASCII extended character set uses 8 bits to represent one character, a total of 256 characters, which is convenient to support common European characters.
- ISO-8859-1 character set:
- Latin code table, alias Latin-1, is used to display the languages used in Europe, including Netherlands, Denmark, German, Italian and Spanish
- ISO-5559-1 uses single byte encoding and is compatible with ASCII encoding.
- GBxxx character set:
- GB: national standard means a set of characters designed to display Chinese.
- GB2312: Simplified Chinese code table. A character less than 127 has the same meaning as the original. However, when two characters larger than 127 are connected together, they represent a Chinese character, which can be combined with more than 7000 simplified Chinese characters. In addition, mathematical symbols, Roman and Greek letters and Japanese Kanas have been compiled. Even the original numbers, punctuation and letters in ASCII have been re encoded by two bytes, which is often called "full angle" characters, Those below the original number 127 are called "half width" characters.
- GBK: the most commonly used Chinese code table. It is an extended specification based on GB2312 standard. It uses a double byte coding scheme and contains 21003 Chinese characters. It is fully compatible with GB2312 standard and supports traditional Chinese characters, Japanese and Korean characters.
- GB18030: latest Chinese code table. It contains 70244 Chinese characters, which are encoded by multiple bytes. Each word can be composed of 1, 2 or 4 bytes. Support the characters of ethnic minorities in China, as well as traditional Chinese characters and Japanese and Korean characters.
- Unicode character set:
- Unicode coding system is designed to express any character in any language. It is a standard in the industry, also known as unified code and standard universal code.
- It uses up to four byte numbers to express each letter, symbol, or text. There are three coding schemes, UTF-8, UTF-16UTF-32. The most commonly used UTF-8 coding.
- UTF-8 encoding can be used to represent any character in Unicode standard. It is the preferred encoding in e-mail, Web pages and other applications for storing or transmitting text. The Internet Engineering Task Force (IETF) requires that all Internet protocols must support UTF-8 coding. Therefore, when we develop Web applications, we also need to use UTF-8 coding. It uses one to four bytes to encode each character. The encoding rules are:
- 128 US-ASCII characters, only one byte encoding is required.
- Latin and other characters require two byte encoding.
- Most common words (including Chinese) are encoded in three bytes.
- Other rarely used Unicode auxiliary characters use four byte encoding.
2.2 problems caused by coding
In IDEA, use FileReader to read the text file in the project. Since the setting of IDEA is the default UTF-8 encoding, there is no problem. However, when reading a text file created in the Windows system, garbled code will appear because the default of the Windows system is GBK coding.
/* FileReader You can read files in the IDEA default encoding format (UTF-8) FileReader Reading the system black t recognition code (Chinese GBK) will produce garbled code */ public class Demo01FileReader { public static void main(String[] args) throws IOException { FileReader fr = new FileReader("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\GBK.txt"); int len = 0; while ((len = fr.read()) != -1){ System.out.println((char) len); } fr.close(); } } Output results: � � �
So how to read GBK encoded files?
2.3 InputStreamReader class
Transform stream Java io. Inaputstreamreader is a subclass of Reader and a bridge from byte stream to character stream. It reads bytes and decodes them into characters using the specified character set. Its character set can be specified by name or accept the default character set of the platform.
Construction method
- InputstreamReader(InputStream in): create a character stream that uses the default character set.
- InputStreamReader(InputStream in, String charsetName): creates a character stream with a specified character set.
package com.itheima.demo03ReverseStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; /* java.io.InputStreamReader extends Reader InputStreamReader:It is a bridge between byte flow and character flow: it uses the specified charset to read bytes and decode them into characters. (decoding: turn what you can't understand into what you can understand) Common member methods inherited from parent class: int read()Read a single character and return. int read(char[] cbuf)Read multiple characters at a time and read the characters into the array. void close()Close the flow and release all resources associated with it. Construction method: InputStreamReader(InputStream in)Create an InputStreamReader that uses the default character set. InputStreamReader(InputStream in,String charsetName)Creates an InputStreamReader that uses the specified character set. Parameters: InputStream in :Byte input stream, which is used to read the bytes saved in the file String charsetName:The specified encoding table name is not case sensitive. It can be utf-8/UTF-8,gbk/GBK Do not specify default use uTF-8 Use steps: 1.Create an InputStreamReader object and pass the byte input stream and the specified encoding table name in the construction method 2.Use the read method in the InputStreamReader object to read the file 3.Release resources matters needing attention: The code table name specified in the construction method must be the same as the file code, otherwise garbled code will occur */ public class Demo03InputStreamReader { public static void main(String[] args) throws IOException { read_utf_8(); read_gbk(); } /* Use InputStreamReader to read files in UTF-8 format */ private static void read_gbk() throws IOException { //1. Create InputStreamReader object and pass byte input stream and specified encoding table name in construction method InputStreamReader isr = new InputStreamReader(new FileInputStream("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\gbk1.txt"), "gbk"); //2. Use the read method in the InputStreamReader object to read the file int len = 0; while ((len = isr.read()) != -1){ System.out.println((char) len); } //3. Release resources isr.close(); } /* Use InputStreamReader to read files in UTF-8 format */ private static void read_utf_8() throws IOException { //1. Create InputStreamReader object and pass byte input stream and specified encoding table name in construction method // InputStreamReader isr = new InputStreamReader(new FileInputStream("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\utf-8.txt"), "utf-8"); InputStreamReader isr = new InputStreamReader(new FileInputStream("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\utf-8.txt"));//No encoding format is specified. The default is utf-8 //2. Use the read method in the InputStreamReader object to read the file int len = 0; while ((len = isr.read()) != -1){ System.out.println((char) len); } //3. Release resources isr.close(); } }
Principle of conversion flow
2.4 OutputStreamWriter class
OutputStreamWriter: it is the bridge between character flow and byte flow: the characters written to it are encoded into the specified byte charset. The character set it uses can be specified by name or explicitly, or it can accept the default character set of the platform.
Construction method:
- OutputStreamWriter(outputStream out) creates an OutputStreamWriter that uses black character encoding.
- OutputStreamWriter(OutputStream out, String charsetName) creates an OutputStreamWriter that uses the specified character set.
import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; /* java.io.OutputStreamWriter extends Writer OutputStreamWriter:It is a bridge between character flow and byte stream: the characters to be written to the stream can be encoded into bytes using the specified charset. (Code: change what you can understand into what you can't understand) Continue common member methods from parent class: - void write(int c)Write a single character. - void write(char[] cbuf)Write character array. - abstract void write(char[] cbuf,int off,int len)Write a part of the character array, the start index of the off array, and the number of characters written by len. - void write(String str)Write string. - void write(String str, int off, int len)Write a part of the string, off the start index of the string, and the number of characters written by Len. - void flush()Flush the buffer of the stream. - void close()Close this stream, but refresh it first. Construction method: OutputStreamWriter(outputStream out)Create an OutputStreamWriter that uses black character encoding. OutputStreamWriter(OutputStream out,String charsetName)Creates an OutputStreamWriter that uses the specified character set. Parameters: OutputStream out:Byte output stream, which can be used to write converted bytes to the file String charsetName:The specified encoding table name is not case sensitive. It can be utf-8/UTF-8,gbk/GBK Do not specify default use UTF-8 Use steps: 1.Create the OutputStreamWriter object and pass the byte output stream and the specified encoding table name in the construction method 2.Use the write method in the OutputStreamWriter object to convert characters into bytes and store them in the buffer (encoding) 3.Use the method flush in the OutputStreamWriter object to flush the bytes in the memory buffer into the file (the process of writing bytes using byte stream) 4.Release resources */ public class Demo02OutputStreamWriter { public static void main(String[] args) throws IOException { //write_utf_8(); write_gbk(); } private static void write_gbk() throws IOException { //1. Create the OutputStreamWriter object and pass the byte output stream and the specified encoding table name in the construction method OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\gbk1.txt"), "GBK"); //2. Use the write method in the OutputStreamWriter object to convert characters into bytes and store them in the buffer (encoding) osw.write("Hello"); //3. Use the method flush in the OutputStreamWriter object to flush the bytes in the memory buffer into the file (the process of writing bytes using byte stream) osw.flush(); //4. Release resources osw.close(); } /* Use the transform stream OutputStreamWriter to write files in UTF-8 format */ private static void write_utf_8() throws IOException { //1. Create the OutputStreamWriter object and pass the byte output stream and the specified encoding table name in the construction method // OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("E:\Java\JavaWorkSpace\enhance_code\exam10\file_directory\utf-8.txt")); Do not specify default use UTF-8 OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\utf-8.txt"), "utf-8"); //2. Use the write method in the OutputStreamWriter object to convert characters into bytes and store them in the buffer (encoding) osw.write("Hello"); //3. Use the method flush in the OutputStreamWriter object to flush the bytes in the memory buffer into the file (the process of writing bytes using byte stream) osw.flush(); //4. Release resources osw.close(); } }
2.5 conversion document code
package com.itheima.demo03ReverseStream; import java.io.*; /* Exercise: converting file encoding Convert GBK encoded text file into UTF-8 encoded text file. analysis: 1.Create an InputStreamReader object, and pass the byte input stream and the specified encoding table name GBK in the construction method 2.Create the OutputStreamWriter object and pass the byte output stream and the specified encoding table name UTF-8 in the construction method 3.Use the read method in the InputStreamReader object to read the file 4.Use the Write method in the OutputStreamWriter object to Write the read data to the file 5.Release resources */ public class Demo04Test { public static void main(String[] args) throws IOException { //1. Create an InputStreamReader object, and pass the byte input stream and the specified encoding table name GBK in the construction method InputStreamReader isr = new InputStreamReader(new FileInputStream("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\GBK.txt"), "gbk"); //2. Create the OutputStreamWriter object and pass the byte output stream and the specified encoding table name UTF-8 in the construction method OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\utf-8_1.txt"), "utf-8"); //3. Use the read method in the InputStreamReader object to read the file int len = 0; while ((len = isr.read()) != -1){ //4. Use the Write method in the OutputStreamWriter object to Write the read data to the file osw.write(len); } //5. Release resources osw.close(); isr.close(); } }
Chapter 3 serialization
3.1 general
Java provides a mechanism for object serialization. An object can be represented by a byte sequence, which contains the data of the object, the type of the object and the attributes stored in the object. After the byte sequence is written out to the file, it is equivalent to persisting the information of an object in the file.
On the contrary, the byte sequence can also be read back from the file, reconstruct the object and deserialize it. Object data, object type and data information stored in the object can be used to create objects in memory. See the figure to understand serialization:
Note: in order to serialize the object of a class successfully, two conditions must be met:
- This class must implement Java io. Serializable interface.
- All properties of this class must be serializable. If a property is not serializable, the property must indicate that it is transient.
If you want to know whether a Java standard class is serializable, please check the class documentation. Checking whether an instance of a class can be serialized is very simple. You only need to check whether the class implements Java io. Serializable interface.
3.2 serialized objects
ObjectOutputStream class is used to serialize an object. The following SerializeDemo example instantiates a Person object and serializes the object into a file.
After the program is executed, a program named person is created Ser file. The program has no output, but you can understand the function of the program through code reading.
Note: when serializing an object to a file, the standard convention of Java is to give a file ser extension.
import java.io.Serializable; /* During serialization and deserialization, NotSerializableException will be thrown without serialization exception Class by implementing Java io. Serializable interface to enable its serialization. A class that does not implement this interface will not be able to serialize or deserialize any of its states. Serializable The interface is also called marked interface The class to be serialized and deserialized must implement the Serializable interface, and a tag will be added to the class When we serialize and deserialize, we will detect whether there is this tag on the class Yes: you can serialize and deserialize No: a NotSerializableException will occur static Keywords: static keywords Static loading takes precedence over non static loading into memory (static loading takes precedence over object entry into memory) Member variables modified by static cannot be serialized. All serialized variables are objects private static int age; oos.writeObject(new Person("Little beauty ", 18); object o = ois.readObject(); Person{name="Little beauty ', age=0} transient Keywords: transient keywords Member variables modified by transient cannot be serialized private transient int age; oos.writeObject(new Person("Little beauty ", 18); object o = ois.readObject(); Person{name="Little beauty ', age=0} */ public class Person implements Serializable{ private String name; // private static int age; // private transient int age; private int age; public Person() { } public Person(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 "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } } import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; /* java.io.ObjectOutputStream extends OutputStream ObjectOutputStream:Serialization stream of object Function: write the object to the file in the form of stream and save it Construction method: ObjectOutputStream(OutputStream out)Creates an ObjectOutputStream that writes to the specified OutputStream. Parameters: OutputStream out:Byte output stream Unique member methods: void writeObject(Object obj)Writes the specified object to ObjectOutputStream. Use steps: 1.Create ObjectOutputStream object and pass byte output stream in construction method 2.Use the method writeObject in the ObjectOutputStream object to write the object to a file 3.Release resources */ public class Demo01ObjectOutputStream { public static void main(String[] args) throws IOException { //1. Create ObjectOutputStream object and transfer byte output stream in construction method ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\person.ser")); //2. Use the method writeObject in ObjectOutputStream object to write the object to the file oos.writeObject(new Person("Little beauty", 18)); //3. Release resources oos.close(); } }
3.3 deserializing objects
The following DeserializeDemo program instance de serializes, E:\Java\JavaWorkSpace\enhance_code\exam10\file_directory\person.ser stores the Person object.
import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; /* java.io.ObjectInputStream extends InputStream ObjectInputStream:Deserialization stream of object Function: read out and use the objects saved in the file in the form of stream Construction method: ObjectInputStream(InputStream in〉Creates an ObjectInputStream read from the specified InputStream Parameters: InputStream in :Byte input stream Unique member methods: Object readObject()Read objects from ObjectInputStream. Use steps: 1.Create an ObjectInputStream object and pass the byte input stream in the construction method 2.Use the method readObject in the ObjectInputStream object to read the file where the object is saved 3.Release resources 4.Use the read object (print) readObject Method declaration threw classnotfoundexception (exception not found in class file) This exception is thrown when the class file of the object does not exist Precondition for deserialization: 1.Class must implement Serializable 2.The class file corresponding to the class must exist */ public class Demo02ObjectInputStream { public static void main(String[] args) throws IOException, ClassNotFoundException { //1. Create objectInputStream object and transfer byte input stream in construction method ObjectInputStream ois = new ObjectInputStream(new FileInputStream("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\person.ser")); //2. Use the method readObject in the ObjectInputStream object to read the file where the object is saved Object o = ois.readObject(); //3. Release resources ois.close(); //4. Use the read object (print) System.out.println(o); } }
Here we should pay attention to the following points:
The try/catch code block in the readObject() method attempts to catch a ClassNotFoundException exception. For a JVM to deserialize an object, it must be a class that can find bytecode. If the JVM cannot find the class during deserialization of the object, a ClassNotFoundException exception is thrown.
3.4 deserialization operation 2
**In addition, when the JVM deserializes the object, the class file can be found, but if the class file is modified after serializing the object, the deserialization operation will also fail and an InvalidclassException will be thrown** The reasons for this exception are as follows:
- The serial version number of the class does not match the version number of the class descriptor read from the stream
- The class contains an unknown data type
- This class has no accessible parameterless constructor
The Serializable interface provides a serial version number to the class to be serialized. serialversionUID this version number is used to verify whether the serialized object and the corresponding class match.
3.5 practice serialization set
import java.io.*; import java.util.ArrayList; /* Exercise: serializing collections When we want to save multiple objects in a file, we can store multiple objects in a collection and serialize and deserialize the collection analysis: 1.Define an ArrayList collection that stores Person objects 2.Store the Person object in the ArrayList collection 3.Create a serialization stream ObjectOutputStream object 4.Serialize the collection using the writeObject method in the ObjectOutputStream object 5.Create a deserialized ObjectInputStream object 6.Use the method readObject in the ObjectInputStream object to read the collection saved in the file 7.Convert the collection of Object type to ArrayList type 8.Traverse the ArrayList collection 9.Release resources */ public class Demo03Test { public static void main(String[] args) throws IOException, ClassNotFoundException { //1. Define an ArrayList collection that stores Person objects ArrayList<Person> list = new ArrayList<>(); //2. Store the Person object in the ArrayList collection list.add(new Person("Zhang San", 18)); list.add(new Person("Li Si", 19)); list.add(new Person("Wang Wu", 20)); //3. Create a serialization stream ObjectOutputStream object ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\list.ser")); //4. Use the writeObject method in the ObjectOutputStream object to serialize the collection oos.writeObject(list); //5. Create a deserialized ObjectInputStream object ObjectInputStream ois = new ObjectInputStream(new FileInputStream("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\list.ser")); //6. Use the method readObject in the ObjectInputStream object to read the collection saved in the file Object o = ois.readObject(); //7. Convert the collection of Object type to ArrayList type ArrayList<Person> list2 = (ArrayList<Person>)o; //8. Traverse the ArrayList set for (Person p : list2){ System.out.println(p); } //9. Release resources ois.close(); oos.close(); } }
Chapter 4 print stream
4.1 General
We usually print the output on the console by calling the print method and println method, both of which are from Java io. Printstream class, which can easily print values of various data types, is a convenient output method.
4.2 PrintStream class
Construction method
- public PrintStream(String fileName): creates a new print stream with the specified file name.
import java.io.FileNotFoundException; import java.io.PrintStream; /* java.io.PrintStream:Print stream PrintStream Added functionality to other output streams to enable them to easily print various data value representations. PrintStream characteristic: 1.Only responsible for data output, not data reading 2.Unlike other output streams, PrintStream will never throw IOException 3.There are special methods, print and println void print((any type of value) void println(Any type of value (and wrap) Construction method: PrintStream(File file):The destination of the output is a file PrintStream(OutputStream out):The destination of the output is a byte output stream PrintStream (String fileName):The destination of the output is a file path PrintStream extends OutputStream Member methods inherited from parent class: - public void close() :Close this output stream and free any system resources associated with this stream. - public void flush():Refresh this output stream and force any buffered output bytes to be written out. - public void write(byte[] b):Writes the b.length byte from the specified byte array to this output stream. - public void write(byte[] b, int off, int len):Write len bytes from the specified byte array and output to this output stream from offset off. - public abstract void write(int b):Outputs the specified bytes to the stream. be careful: If the write method inherited from the parent class is used to write data, the code table 97 - > A will be queried when viewing the data If you use your own unique method print/println to write data, the written data will be output as is 97 - > 97 */ public class Demo01PrintStream { public static void main(String[] args) throws FileNotFoundException { System.out.println("HelloWorld"); //Create a PrintStream object and bind the destination to be output in the construction method PrintStream ps = new PrintStream("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\print.txt"); //If the write method inherited from the parent class is used to write data, the code table 97 - > A will be queried when viewing the data ps.write(97); //If you use your own unique method print/println to write data, the written data will be output as 97 - > 97 ps.println(97); ps.println(8.8); ps.println('a'); //Release resources ps.close(); } }
Change print flow direction
System.out is of PrintStream type, but its flow direction is specified by the system and printed on the console. However, since it is a flow object, we can play a "trick" to change its flow direction.
import java.io.FileNotFoundException; import java.io.PrintStream; /* You can change the destination of the output statement (the flow direction of the print stream) Output statement, which is output on the console by default Use system The setout method changes the destination of the output statement to the destination of the print stream passed in the parameter static void setOut(PrintStream out) Reassign the standard output stream. */ public class Demo02PrintStream { public static void main(String[] args) throws FileNotFoundException { System.out.println("I output on the console"); PrintStream ps = new PrintStream("E:\\Java\\JavaWorkSpace\\enhance_code\\exam10\\file_directory\\printStream_aim_space.txt"); System.setOut(ps); System.out.println("I output in the destination of the print stream"); } }