[buffer stream, conversion stream, serialization stream]

[buffer stream, conversion stream, serialization stream]

Today's goal

  • Processing of IO resources.
    • Finally release resources
    • Try with resources, a new technology from jdk 1.7
  • Buffer stream
    • Improve the performance of reading and writing data in byte stream and character stream.
  • Conversion flow
    • It can solve the problem of reading garbled codes with different codes.
  • serialize
    • You can store Java objects in files.
  • Print stream
    • It can easily write data out, and support writing any type of data to files. It is very convenient, simple and powerful.
  • Attribute set
    • Is a Map collection.

Teaching objectives

  • The ability to read data to a program using a byte input stream

    • InputStream is = new FileInputStream("file path");
    • is.read(): read a byte
    • is.read(byte[] buffer): read a byte array.
  • Be able to understand the principle of the read(byte []) method for reading data

    • read(byte []): read byte data into a byte array, return the number of bytes read, and return - 1 after reading
  • Can use byte stream to copy files

    (1)Create a byte input stream pipeline to connect with the source file.
    (2)Create a byte output stream to connect with the target file.
    (3)Create a byte array as a bucket
    (4)Read the data from the byte input stream pipeline and write it to the byte output stream pipeline.
    (5)Close resource!
    
  • Five ways to write data using FileWriter

    a.public void write(int c):Write a character out
    b.public void write(String c)Write a string:
    c.public void write(char[] buffer):Write a character array
    d.public void write(String c ,int pos ,int len):Write part of the string out
    e.public void write(char[] buffer,int pos ,int len):Write a part of a character array
    
  • Be able to tell the difference between closing and refreshing methods in FileWriter

    • Turn off include refresh
    • After closing, the stream cannot continue to be used
    • After refreshing, the stream can continue to be used
  • Can use FileWriter to write data to realize line feed and additional write

    • The additional pipes are: Writer fw = new FileWriter("Day10Demo/out03.txt" , true); // Add pipe!!
      Line feed: fw.write("\r\n"); // Write a newline character of a string!
      
  • Can use FileReader to read data one character at a time

  • Can use FileReader to read data one character array at a time

    • Reader fr = new FileReader("Day10Demo/dlei02.txt");
      
      char[] buffer = new char[1024]; // Define a bucket / / 3 + 3 + 1
      int len ;  // Record the number of characters read each time
      while((len = fr.read(buffer))!=-1){
           String rs = new String(buffer,0,len);
           System.out.print(rs);
      }
      
  • You can use the load method of Properties to load the configuration information in the file

    // 1. Define a byte input stream pipeline to connect with the attribute source file
    InputStream is = new BufferedInputStream(new FileInputStream("Day10Demo/users.properties"));
    // 2. Create an attribute set object to load the data in the file.
    Properties pro = new Properties();
    System.out.println(pro);
    // 3. Load the byte input stream file data of the attribute set object into the attribute set object pro.
    pro.load(is);
    System.out.println(pro);
    
    System.out.println(pro.getProperty("dlei"));
    System.out.println(pro.getProperty("admin"));
    
  • Be able to use byte buffer stream to read data to program

    • Just pack the previous stream!!
  • Ability to write data to a file using a byte buffer stream

    • Just pack the previous stream!!
  • The function and basic usage of character buffer stream can be clarified

    • Improve performance! Read and write character performance.
  • Ability to use special features of buffered streams

    • There are too many bufferedreaders in the character input buffer stream. Read by line: readLine();
    • The character output buffer stream BufferedWriter has more line feed methods: newLine();
  • Be able to explain the meaning of coding table

    • The same code can be read without garbled code
    • Reading different codes will cause garbled codes
  • Be able to use the conversion stream to read the text file with the specified encoding

    • // Code: UTF-8 file: GBK(ab I love you)
      // 1. First extract the original byte stream of the file: o o oo oo oo
      InputStream is = new FileInputStream("D:\\itcast\\Open course of network programming\\Netty.txt");
      // 2. Convert byte input stream to character input stream: use character input to convert stream.
      //Reader isr = new InputStreamReader(is); //  The default encoding is UTF-8 to character stream.
      Reader isr = new InputStreamReader(is ,"GBK"); // Specifies the encoding to convert a byte stream to a character stream
      // 3. Wrap the character stream into a high-level buffered character input stream
      BufferedReader  br = new BufferedReader(isr);
      // 4. Read by line
      String line ;
      while((line = br.readLine())!=null){
          System.out.println(line);
      }
      
  • Can use the conversion stream to write a text file with a specified encoding

    • // 1. Write a byte output to the file
      OutputStream os = new FileOutputStream("Day10Demo/out05.txt");
      
      // 2. Convert byte output stream to character output stream: convert with default encoding!!
      // Writer fw = new OutputStreamWriter(os);  //  Character: UTF-8
      Writer fw = new OutputStreamWriter(os,"GBK");  // Character: GBK
      // 3. Wrap the character output stream into a buffered character output stream
      BufferedWriter  bw = new BufferedWriter(fw);
      
      bw.write("I love you China!");
      bw.write("I love you China!");
      bw.close();
      
  • Ability to write out objects to files using serialized streams

    • ObjectOutputStream

    • // 1. Create a User object
      User user = new User("Rola Takizawa","dongjing-lzll","15longze",21);
      // Requirement: serialize Java objects into local files.
      // 2. Create a low-level byte output flow to the target file.
      OutputStream os = new FileOutputStream("Day10Demo/obj.dat");
      // 3. Package low-level byte output stream into high-level object byte output stream:
      // Because only the object byte output stream can serialize objects here!
      ObjectOutputStream oos = new ObjectOutputStream(os);
      // 4. Start serializing objects using the object serialization stream.
      oos.writeObject(user);
      oos.close();
      System.out.println("Serialization succeeded!");
      
  • Ability to read files into programs using deserialization streams

    • // 1. Define a byte input stream to connect with the source file of Java object
      InputStream is = new FileInputStream("Day10Demo/obj.dat");
      
      // 2. Wrap the low-level byte input stream into the high-level object byte input stream
      ObjectInputStream ois = new ObjectInputStream(is);
      
      // 3. Reverse sequence object
      User user = (User) ois.readObject();
      
      System.out.println(user);
      

Chapter 1 character stream

There may be a small problem when using byte stream to read text files. When Chinese characters are encountered, complete characters may not be displayed because a Chinese character may occupy multiple bytes of storage. Therefore, Java provides some character stream classes to read and write data in character units, which are specially used to process text files.

1.1 character input stream [Reader]

java. io. The reader abstract class is a superclass that represents all classes used to read character streams. It can read character information into memory. It defines the basic common function method of character input stream.

  • public void close(): close the flow and release any system resources associated with the flow.
  • public int read(): reads a character from the input stream.
  • public int read(char[] cbuf): reads some characters from the input stream and stores them in the character array cbuf.

1.2 FileReader class

java. io. The FileReader class is a convenient class for reading character files. The system default character encoding and default byte buffer are used during construction.

Tips:

  1. Character encoding: the correspondence rule between bytes and characters. The Chinese code of Windows system is GBK code table by default.

UTF-8 in idea

  1. Byte buffer: a byte array used to temporarily store byte data.

Construction method

  • FileReader (File): create a new FileReader and give the File object to be read.
  • FileReader(String fileName): create a new FileReader and give the name of the file to be read.

When you create a stream object, you must pass in a file path. Similar to FileInputStream.

  • For example, the code is as follows:
public class FileReaderConstructor throws IOException{
    public static void main(String[] args) {
   	 	// Create a stream object using a File object
        File file = new File("a.txt");
        FileReader fr = new FileReader(file);
      
        // Create a stream object with a file name
        FileReader fr = new FileReader("b.txt");
    }
}

Read character data

  1. Read character: the read method can read data one character at a time, promote it to int type, read it to the end of the file, return - 1, read it circularly, and demonstrate the use of the code:
public class FRRead {
    public static void main(String[] args) throws IOException {
      	// Create a stream object with a file name
       	FileReader fr = new FileReader("read.txt");
      	// Define variables and save data
        int b ;
        // Cyclic reading
        while ((b = fr.read())!=-1) {
            System.out.println((char)b);
        }
		// close resource
        fr.close();
    }
}
Output results:
black
 horse
 Course
 order
 member

Tip: Although a character is read, it will be automatically promoted to int type.

  1. Use the character array to read: read(char[] cbuf). Each time the length of b is read into the array, return the number of valid characters read. When reading to the end, return - 1. Code usage demonstration:
public class FRRead {
    public static void main(String[] args) throws IOException {
      	// Create a stream object with a file name
       	FileReader fr = new FileReader("read.txt");
      	// Define variables and save the number of valid characters
        int len ;
        // Defines a character array as a container for character data
         char[] cbuf = new char[2];
        // Cyclic reading
        while ((len = fr.read(cbuf))!=-1) {
            System.out.println(new String(cbuf));
        }
		// close resource
        fr.close();
    }
}
Output results:
dark horse
 program
 Member order

Get valid character improvements, code usage demonstration:

public class FISRead {
    public static void main(String[] args) throws IOException {
      	// Create a stream object with a file name
       	FileReader fr = new FileReader("read.txt");
      	// Define variables and save the number of valid characters
        int len ;
        // Defines a character array as a container for character data
        char[] cbuf = new char[2];
        // Cyclic reading
        while ((len = fr.read(cbuf))!=-1) {
            System.out.println(new String(cbuf,0,len));
        }
    	// close resource
        fr.close();
    }
}

Output results:
dark horse
 program
 member

1.3 character output stream [Writer]

java. io. The writer abstract class is a superclass that represents all classes used to write out the character stream and writes the specified character information to the destination. It defines the basic common function method of byte output stream.

  • public abstract void close(): close this output stream and release any system resources associated with this stream.
  • public abstract void flush(): flushes this output stream and forces any buffered output characters to be written out.
  • public void write(int c): write out a character.
  • public void write(char[] cbuf): writes the b.length character out of the specified character array to this output stream.
  • public abstract void write(char[] b, int off, int len): write the len character from the specified character array and output it to this output stream from the offset off.
  • public void write(String str): write out a string.

1.4 FileWriter class

java. io. The filewriter class is a convenient class for writing characters to files. The system default character encoding and default byte buffer are used during construction.

Construction method

  • FileWriter (File): create a new FileWriter and give the File object to be read.
  • FileWriter(String fileName): create a new FileWriter and give the name of the file to be read.

When you create a stream object, you must pass in a file path, similar to FileOutputStream.

  • For example, the code is as follows:
public class FileWriterConstructor {
    public static void main(String[] args) throws IOException {
   	 	// Create a stream object using a File object
        File file = new File("a.txt");
        FileWriter fw = new FileWriter(file);
      
        // Create a stream object with a file name
        FileWriter fw = new FileWriter("b.txt");
    }
}

Basic write data

Write out characters: write(int b) method can write out character data one at a time. Code usage demonstration:

public class FWWrite {
    public static void main(String[] args) throws IOException {
        // Create a stream object with a file name
        FileWriter fw = new FileWriter("fw.txt");     
      	// Write data
      	fw.write(97); // Write the first character
      	fw.write('b'); // Write the second character
      	fw.write('C'); // Write the third character
      	fw.write(30000); // Write the fourth character. 30000 in the Chinese coding table corresponds to a Chinese character.
      
      	/*
        [Note: when closing resources, it is different from FileOutputStream.
      	 If it is not closed, the data is only saved to the buffer, not to the file.
        */
        // fw.close();
    }
}
Output results:
abC field

Tips:

  1. Although the parameter is four bytes of int type, only one character of information will be reserved.
  2. The close method is not called, and the data is only saved to the buffer and not written out to the file.

Close and refresh

Because of the built-in buffer, characters cannot be written out to the file without closing the output stream. However, closed stream objects cannot continue to write data. If we want to write data and continue to use the stream, we need the flush method.

  • Flush: flush the buffer, and the stream object can continue to be used.
  • Close: close the flow and release system resources. The buffer is flushed before closing.

Code usage demonstration:

public class FWWrite {
    public static void main(String[] args) throws IOException {
        // Create a stream object with a file name
        FileWriter fw = new FileWriter("fw.txt");
        // Write out the data through flush
        fw.write('brush'); // Write the first character
        fw.flush();
        fw.write('new'); // Continue to write the second character and write successfully
        fw.flush();
      
      	// Write out the data through close
        fw.write('shut'); // Write the first character
        fw.close();
        fw.write('close'); // Continue to write the second character, [error] Java io. IOException: Stream closed
        fw.close();
    }
}

Tip: even if the flush method writes out data, the close method should be called at the end of the operation to release system resources.

Write other data

  1. Write out the character array: write(char[] cbuf) and write(char[] cbuf, int off, int len). You can write out the data in the character array each time. The usage is similar to FileOutputStream. The code usage demonstration is as follows:
public class FWWrite {
    public static void main(String[] args) throws IOException {
        // Create a stream object with a file name
        FileWriter fw = new FileWriter("fw.txt");     
      	// Convert string to byte array
      	char[] chars = "Dark horse programmer".toCharArray();
      
      	// Write out character array
      	fw.write(chars); // Dark horse programmer
        
		// Write 2 bytes starting from index 2. Index 2 is' process', two bytes, that is' program '.
        fw.write(b,2,2); // program
      
      	// close resource
        fos.close();
    }
}
  1. Write out string: write(String str) and write(String str, int off, int len). You can write out the data in the string each time, which is more convenient. Code usage demonstration:
public class FWWrite {
    public static void main(String[] args) throws IOException {
        // Create a stream object with a file name
        FileWriter fw = new FileWriter("fw.txt");     
      	// character string
      	String msg = "Dark horse programmer";
      
      	// Write out character array
      	fw.write(msg); //Dark horse programmer
      
		// Write 2 bytes starting from index 2. Index 2 is' process', two bytes, that is' program '.
        fw.write(msg,2,2);	// program
      	
        // close resource
        fos.close();
    }
}
  1. Continue and line feed: the operation is similar to FileOutputStream.
public class FWWrite {
    public static void main(String[] args) throws IOException {
        // Create a stream object with a file name to continue writing data
        FileWriter fw = new FileWriter("fw.txt",true);     
      	// Write out string
        fw.write("dark horse");
      	// Write line breaks
      	fw.write("\r\n");
      	// Write out string
  		fw.write("programmer");
      	// close resource
        fw.close();
    }
}
Output results:
dark horse
 programmer

Tip: character stream can only operate text files, not pictures, videos and other non text files.

When we simply read or write text files, we use character stream. In other cases, we use byte stream

Chapter II processing of IO resources

1.2 JDK7 pretreatment

In the previous introductory exercise, we have been throwing exceptions, which cannot be handled in the actual development. It is recommended to use try catch... Finally code block, exception handling part, code usage demonstration:

public class HandleException1 {
    public static void main(String[] args) {
      	// Declare variable
        FileWriter fw = null;
        try {
            //Create flow object
            fw = new FileWriter("fw.txt");
            // Write data
            fw.write("Dark horse programmer"); //Dark horse programmer
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

1.3 handling of JDK7

You can also use the JDK7 optimized try with resource statement, which ensures that each resource is closed at the end of the statement. The so-called resource refers to the object that must be closed after the program is completed.

Format:

try (Create a stream object statement, if more than one,use';'separate) {
	// Read and write data
} catch (IOException e) {
	e.printStackTrace();
}

Code usage demonstration:

public class HandleException2 {
    public static void main(String[] args) {
      	// Create flow object
        try ( FileWriter fw = new FileWriter("fw.txt"); ) {
            // Write data
            fw.write("Dark horse programmer"); //Dark horse programmer
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Chapter 3 attribute set

3.1 general

java.util.Properties inherit from Hashtable to represent a persistent property set. It uses key value structure to store data, and each key and its corresponding value are a string. This class is also used by many Java classes. For example, when obtaining system properties, system The getproperties method returns a properties object.

3.2 Properties class

Construction method

  • public Properties(): create an empty property list.

Basic storage methods

  • public Object setProperty(String key, String value): save a pair of properties.
  • public String getProperty(String key): use the key specified in this property list to search for property values.
  • Public set < string > stringpropertynames(): a collection of names of all keys.
public class ProDemo {
    public static void main(String[] args) throws FileNotFoundException {
        // Create property set object
        Properties properties = new Properties();
        // Add key value pair element
        properties.setProperty("filename", "a.txt");
        properties.setProperty("length", "209385038");
        properties.setProperty("location", "D:\\a.txt");
        // Print property set objects
        System.out.println(properties);
        // Get the attribute value through the key
        System.out.println(properties.getProperty("filename"));
        System.out.println(properties.getProperty("length"));
        System.out.println(properties.getProperty("location"));

        // Traverse the property set to get the collection of all keys
        Set<String> strings = properties.stringPropertyNames();
        // Print key value pairs
        for (String key : strings ) {
          	System.out.println(key+" -- "+properties.getProperty(key));
        }
    }
}
Output results:
{filename=a.txt, length=209385038, location=D:\a.txt}
a.txt
209385038
D:\a.txt
filename -- a.txt
length -- 209385038
location -- D:\a.txt

Flow related methods

  • public void load(InputStream inStream): read key value pairs from byte input stream.

The byte input stream is used in the parameter. Through the stream object, it can be associated with a file, so that the data in the text can be loaded. Text data format:

filename=a.txt
length=209385038
location=D:\a.txt

Load code demo:

public class ProDemo2 {
    public static void main(String[] args) throws FileNotFoundException {
        // Create property set object
        Properties pro = new Properties();
        // Load information from text to property set
        pro.load(new FileInputStream("read.txt"));
        // Traversal set merge print
        Set<String> strings = pro.stringPropertyNames();
        for (String key : strings ) {
          	System.out.println(key+" -- "+pro.getProperty(key));
        }
     }
}
Output results:
filename -- a.txt
length -- 209385038
location -- D:\a.txt

Tip: the data in the text must be in the form of key value pairs, which can be separated by spaces, equal signs, colons and other symbols.

Chapter 4 buffer flow

Yesterday I learned some basic streams. As an introduction to IO streams, today we will see some more powerful streams. For example, a buffer stream that can read and write efficiently, a conversion stream that can convert encoding, a serialization stream that can persist storage objects, and so on. These more powerful flows are created on the basis of basic flow objects, just like warriors wearing armor, which is equivalent to an enhancement of basic flow objects.

4.1 General

Buffered stream, also known as efficient stream, is an enhancement to the 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.

4.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.

For example, the code is as follows:

// Create byte buffered input stream
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("bis.txt"));
// Create byte buffered output stream
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("bos.txt"));

Efficiency test

The query API and the buffer stream read-write method are consistent with the basic stream. We test its efficiency by copying large files (375MB).

  1. Basic flow, code as follows:
public class BufferedDemo {
    public static void main(String[] args) throws FileNotFoundException {
        // Record start time
      	long start = System.currentTimeMillis();
		// Create flow object
        try (
        	FileInputStream fis = new FileInputStream("jdk8.exe");
        	FileOutputStream fos = new FileOutputStream("copy.exe")
        ){
        	// Read and write data
            int b;
            while ((b = fis.read()) != -1) {
                fos.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
		// Record end time
        long end = System.currentTimeMillis();
        System.out.println("Normal stream replication time:"+(end - start)+" millisecond");
    }
}

More than ten minutes have passed...
  1. Buffer stream, the code is as follows:
public class BufferedDemo {
    public static void main(String[] args) throws FileNotFoundException {
        // Record start time
      	long start = System.currentTimeMillis();
		// Create flow object
        try (
        	BufferedInputStream bis = new BufferedInputStream(new FileInputStream("jdk8.exe"));
	     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.exe"));
        ){
        // Read and write data
            int b;
            while ((b = bis.read()) != -1) {
                bos.write(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
		// Record end time
        long end = System.currentTimeMillis();
        System.out.println("Buffer stream copy time:"+(end - start)+" millisecond");
    }
}

Buffer stream copy time:8016 millisecond

How can it be faster?

The code of using array is as follows:

public class BufferedDemo {
    public static void main(String[] args) throws FileNotFoundException {
      	// Record start time
        long start = System.currentTimeMillis();
		// Create flow object
        try (
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream("jdk8.exe"));
		 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.exe"));
        ){
          	// Read and write data
            int len;
            byte[] bytes = new byte[8*1024];
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0 , len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
		// Record end time
        long end = System.currentTimeMillis();
        System.out.println("Buffer stream uses array copy time:"+(end - start)+" millisecond");
    }
}
Buffer stream uses array copy time:666 millisecond

4.3 character buffer stream

Construction method

  • public BufferedReader(Reader in): create a new buffered input stream.
  • public BufferedWriter(Writer out): create a new buffered output stream.

For example, the code is as follows:

// Create character buffered input stream
BufferedReader br = new BufferedReader(new FileReader("br.txt"));
// Create character buffered output stream
BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));

Unique method

The basic method of character buffer stream is the same as that of ordinary character stream. We won't elaborate on it. Let's look at their unique methods.

  • BufferedReader: public String readLine(): read a line of text.
  • BufferedWriter: public void newLine(): write a line separator, and the symbol is defined by the system attribute.

The readLine method is demonstrated with the following code:

public class BufferedReaderDemo {
    public static void main(String[] args) throws IOException {
      	 // Create flow object
        BufferedReader br = new BufferedReader(new FileReader("in.txt"));
		// Define a string and save a line of read text
        String line  = null;
      	// Loop reading. null is returned after reading
        while ((line = br.readLine())!=null) {
            System.out.print(line);
            System.out.println("------");
        }
		// Release resources
        br.close();
    }
}

The newLine method is demonstrated with the following code:

public class BufferedWriterDemo throws IOException {
  public static void main(String[] args) throws IOException  {
    	// Create flow object
  	BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
    	// Write data
      bw.write("dark horse");
    	// Write line breaks
      bw.newLine();
      bw.write("program");
      bw.newLine();
      bw.write("member");
      bw.newLine();
  	// Release resources
      bw.close();
  }
}
Output effect:
dark horse
 program
 member

4.4 exercise: text sorting

Please restore the text information to order.

3.Shi Zhong, Shi Lang Guo Youzhi, Fei Yi, Dong Yun, etc. 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. I was foolish to think that there are no big or small things in the palace. I learned it and consulted it. Then I implemented it, which will benefit the people, fill the gaps and benefit the people.
8.May your majesty entrust his minister to revive the thief. If it doesn't work, he will punish his minister's crime and Sue the spirit of the former Emperor. If there are no words to promote morality, the slowness of you, Yi and Yun will be blamed to show their guilt; Your majesty is also advised to seek advice on his own, so as to understand the good way, observe and accept the elegant words, and deeply pursue the last edict of the former Emperor. I am very grateful.
4.The general Xiang Chong, who is both gentle and gentle, knows the military well. He tried it in the past. The former Emperor called it Neng, which is supervised by the public 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 done, but the middle road collapsed. Today, Yizhou is weak. This is the autumn of crisis. However, the ministers of the guards 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's better to open up the saint's hearing, to honor the legacy of the former Emperor and the spirit of great people with lofty ideals. It's better not to belittle yourself, quote words unjustly, and plug the road of loyal admonition.
9.Today, we should stay away from it. We 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. It has been a year since I was ordered to be in danger at the time of defeat.
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 profit and loss and making good advice, it is also the responsibility of you, Yi and permission.
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.

case analysis

  1. Read text information line by line.
  2. Parse text information into a collection.
  3. Traverse the collection and write out the text information in order.

Case realization

public class BufferedTest {
    public static void main(String[] args) throws IOException {
        // Create a map set and save text data. The key is sequence number and the value is text
        HashMap<String, String> lineMap = new HashMap<>();

        // Create flow object
        BufferedReader br = new BufferedReader(new FileReader("in.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));

        // Read data
        String line  = null;
        while ((line = br.readLine())!=null) {
            // Parse text
            String[] split = line.split("\\.");
            // Save to collection
            lineMap.put(split[0],split[1]);
        }
        // Release resources
        br.close();

        // Traversal map set
        for (int i = 1; i <= lineMap.size(); i++) {
            String key = String.valueOf(i);
            // Get text in map
            String value = lineMap.get(key);
          	// Write the spliced text
            bw.write(key+"."+value);
          	// Write line breaks
            bw.newLine();
        }
		// Release resources
        bw.close();
    }
}

Chapter V conversion flow

5.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 results 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 f symbols can be displayed. On the contrary, storing according to rule A and parsing according to rule B will lead to garbled code.

  • Character Encoding: a set of correspondence rules between natural language characters and binary numbers.

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 our final concern.

  • 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, Spanish, etc.
    • ISO-5559-1 uses single byte encoding and is compatible with ASCII encoding.
  • GBxxx character set:
    • GB means national standard, which is a set of character sets 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. 70244 Chinese characters are included, and multi byte coding is adopted. 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, 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 bytes of numbers to express each letter, symbol, or text. There are three coding schemes, UTF-8, UTF-16 and UTF-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 should also use UTF-8 coding. It uses one to four bytes to encode each character. The encoding rules are as follows:
      1. 128 US-ASCII characters, only one byte encoding is required.
      2. Latin and other characters require two byte encoding.
      3. Most common words (including Chinese) are encoded in three bytes.
      4. Other rarely used Unicode auxiliary characters use four byte encoding.

5.2 problems caused by coding

In IDEA, use FileReader to read the text file in the project. Since the IDEA is set to the default UTF-8 encoding, there is no problem. However, when reading text files created in the Windows system, garbled code will appear because the default of the Windows system is GBK coding.

public class ReaderDemo {
    public static void main(String[] args) throws IOException {
        FileReader fileReader = new FileReader("E:\\File_GBK.txt");
        int read;
        while ((read = fileReader.read()) != -1) {
            System.out.print((char)read);
        }
        fileReader.close();
    }
}
Output results:
���

So how to read GBK encoded files?

5.3 InputStreamReader class

Transform stream Java io. Inputstreamreader 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): creates a character stream that uses the default character set.
  • InputStreamReader(InputStream in, String charsetName): creates a character stream with a specified character set.

For example, the code is as follows:

InputStreamReader isr = new InputStreamReader(new FileInputStream("in.txt"));
InputStreamReader isr2 = new InputStreamReader(new FileInputStream("in.txt") , "GBK");

Specify encoding read

public class ReaderDemo2 {
    public static void main(String[] args) throws IOException {
      	// Define the file path. The file is gbk encoded
        String FileName = "E:\\file_gbk.txt";
      	// Create a stream object with the default UTF8 encoding
        InputStreamReader isr = new InputStreamReader(new FileInputStream(FileName));
      	// Create a stream object and specify the GBK encoding
        InputStreamReader isr2 = new InputStreamReader(new FileInputStream(FileName) , "GBK");
        
        
		// Define variables and save characters
        int read;
      	// Use the default encoding character stream to read, garbled
        while ((read = isr.read()) != -1) {
            System.out.print((char)read); // ��Һ�
        }
        isr.close();
      
      	// Read using the specified encoded character stream and parse normally
        while ((read = isr2.read()) != -1) {
            System.out.print((char)read);// hello everyone
        }
        isr2.close();
    }
}

5.4 OutputStreamWriter class

Transform stream Java io. Outputstreamwriter is a subclass of Writer and a bridge from character stream to byte stream. Encodes characters into bytes using the specified character set. Its character set can be specified by name or accept the default character set of the platform.

Construction method

  • OutputStreamWriter(OutputStream in): creates a character stream that uses the default character set.
  • OutputStreamWriter(OutputStream in, String charsetName): creates a character stream with a specified character set.

For example, the code is as follows:

OutputStreamWriter isr = new OutputStreamWriter(new FileOutputStream("out.txt"));
OutputStreamWriter isr2 = new OutputStreamWriter(new FileOutputStream("out.txt") , "GBK");

Specify encoding write out

public class OutputDemo {
    public static void main(String[] args) throws IOException {
      	// Define file path
        String FileName = "E:\\out.txt";
      	// Create a stream object with the default UTF8 encoding
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(FileName));
        // Write data
      	osw.write("Hello"); // Save as 6 bytes
        osw.close();
      	
		// Define file path
		String FileName2 = "E:\\out2.txt";
     	// Create a stream object and specify the GBK encoding
        OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream(FileName2),"GBK");
        // Write data
      	osw2.write("Hello");// Save as 4 bytes
        osw2.close();
    }
}

Transformation flow understanding diagram

The conversion stream is a bridge between bytes and characters!

5.5 exercise: converting file codes

Convert GBK encoded text files into UTF-8 encoded text files.

case analysis

  1. Specify the GBK encoded conversion stream and read the text file.
  2. Use the UTF-8 encoded conversion stream to write out the text file.

Case realization

public class TransDemo {
   public static void main(String[] args) {      
    	// 1. Define file path
     	String srcFile = "file_gbk.txt";
        String destFile = "file_utf8.txt";
		// 2. Create a flow object
    	// 2.1 convert the input stream and specify the GBK code
        Reader isr = new InputStreamReader(new FileInputStream(srcFile) , "GBK");
    	// 2.2 convert output stream, default utf8 encoding
        Writer osw = new OutputStreamWriter(new FileOutputStream(destFile));
		// 3. Read and write data
    	// 3.1 defining arrays
        char[] cbuf = new char[1024];
    	// 3.2 defining length
        int len;
    	// 3.3 cyclic reading
        while ((len = isr.read(cbuf))!=-1) {
            // Loop write
          	osw.write(cbuf,0,len);
        }
    	// 4. Release resources
        osw.close();
        isr.close();
  	}
}

Chapter 6 serialization

6.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. Look at the picture and understand the serialization: [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-doBXgYgg-1641466390314)(img/3_xuliehua.jpg)]

6.2 ObjectOutputStream class

java.io.ObjectOutputStream class writes out the original data type of Java object to a file to realize the persistent storage of the object.

Construction method

  • public ObjectOutputStream(OutputStream out): creates an ObjectOutputStream that specifies the OutputStream.

For example, the code is as follows:

FileOutputStream fileOut = new FileOutputStream("employee.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOut);

Serialization operation

  1. To serialize an object, two conditions must be met:
  • This class must implement Java io. Serializable interface. Serializable is a tag interface. Classes that do not implement this interface will not serialize or deserialize any state, and will throw NotSerializableException.
  • All properties of this class must be serializable. If a property does not need to be serializable, the property must be marked as transient and modified with the transient keyword.
public class Employee implements java.io.Serializable {
    public String name;
    public String address;
    public transient int age; // Transient is a transient decorated member and will not be serialized
    public void addressCheck() {
      	System.out.println("Address  check : " + name + " -- " + address);
    }
}

2. Write out object methods

  • public final void writeObject (Object obj): writes out the specified object.
public class SerializeDemo{
   	public static void main(String [] args)   {
    	Employee e = new Employee();
    	e.name = "zhangsan";
    	e.address = "beiqinglu";
    	e.age = 20; 
    	try {
      		// Create serialized stream object
          ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.txt"));
        	// Write out object
        	out.writeObject(e);
        	// Release resources
        	out.close();
        	fileOut.close();
        	System.out.println("Serialized data is saved"); // Name and address are serialized, age is not serialized.
        } catch(IOException i)   {
            i.printStackTrace();
        }
   	}
}
Output results:
Serialized data is saved

6.3 ObjectInputStream class

ObjectInputStream deserializes the stream and restores the original data previously serialized with ObjectOutputStream to objects.

Construction method

  • public ObjectInputStream(InputStream in): creates an ObjectInputStream that specifies an InputStream.

Deserialization operation 1

If we can find the class file of an object, we can deserialize it and call the ObjectInputStream method to read the object:

  • public final Object readObject(): reads an object.
public class DeserializeDemo {
   public static void main(String [] args)   {
        Employee e = null;
        try {		
             // Create deserialized stream
             FileInputStream fileIn = new FileInputStream("employee.txt");
             ObjectInputStream in = new ObjectInputStream(fileIn);
             // Read an object
             e = (Employee) in.readObject();
             // Release resources
             in.close();
             fileIn.close();
        }catch(IOException i) {
             // Catch other exceptions
             i.printStackTrace();
             return;
        }catch(ClassNotFoundException c)  {
        	// The capture class cannot find an exception
             System.out.println("Employee class not found");
             c.printStackTrace();
             return;
        }
        // No abnormality, direct printout
        System.out.println("Name: " + e.name);	// zhangsan
        System.out.println("Address: " + e.address); // beiqinglu
        System.out.println("age: " + e.age); // 0
    }
}

For a JVM to deserialize an object, it must be a class that can find a class file. If the class file of the class cannot be found, a ClassNotFoundException exception is thrown.

Deserialization operation 2

**In addition, when the JVM deserializes the object, the class file can be found, but 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.

public class Employee implements java.io.Serializable {
     // Add serial version number
     private static final long serialVersionUID = 1L;
     public String name;
     public String address;
     // Add a new attribute, recompile, deserialize, and assign this attribute as the default value
     public int eid; 

     public void addressCheck() {
         System.out.println("Address  check : " + name + " -- " + address);
     }
}

6.4 exercise: serializing collections

  1. Serialize the collection containing multiple custom objects and save it to the list Txt file.
  2. Deserialize list Txt, and traverse the collection to print object information.

case analysis

  1. Save several student objects into the collection.
  2. Serialize the collection.
  3. During deserialization reading, you only need to read it once and convert it to collection type.
  4. Traverse the collection, you can print all student information

Case realization

public class SerTest {
	public static void main(String[] args) throws Exception {
		// Create student object
		Student student = new Student("Lao Wang", "laow");
		Student student2 = new Student("Lao Zhang", "laoz");
		Student student3 = new Student("Lao Li", "laol");

		ArrayList<Student> arrayList = new ArrayList<>();
		arrayList.add(student);
		arrayList.add(student2);
		arrayList.add(student3);
		// Serialization operation
		// serializ(arrayList);
		
		// Deserialization  
		ObjectInputStream ois  = new ObjectInputStream(new FileInputStream("list.txt"));
		// Read the object and force it to ArrayList type
		ArrayList<Student> list  = (ArrayList<Student>)ois.readObject();
		
      	for (int i = 0; i < list.size(); i++ ){
          	Student s = list.get(i);
        	System.out.println(s.getName()+"--"+ s.getPwd());
      	}
	}

	private static void serializ(ArrayList<Student> arrayList) throws Exception {
		// Create serialized stream 
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("list.txt"));
		// Write out object
		oos.writeObject(arrayList);
		// Release resources
		oos.close();
	}
}

Chapter 7 print stream

7.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.

7.2 PrintStream class

  • public PrintStream(String fileName): creates a new print stream with the specified file name.

For example, the code is as follows:

PrintStream ps = new PrintStream("ps.txt");

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 stream object, we can play a "trick" to output the data to a specified text file.

public class PrintDemo {
    public static void main(String[] args) throws IOException {
		// Call the print stream of the system, and the console outputs 97 directly
        System.out.println(97);
      
		// Create a print stream and specify the name of the file
        PrintStream ps = new PrintStream("ps.txt");
      	
      	// Set the print flow direction of the system and output it to ps.txt
        System.setOut(ps);
      	// Call the print stream of the system and output 97 in ps.txt
        System.out.println(97);
    }
}

Keywords: Java

Added by bubatalazi on Thu, 06 Jan 2022 13:31:48 +0200