IO common classes of Java

IO common classes

1, File class

1.1 general

File class: the only class in the IO package in java related to the operation of the file itself. Using this file class, we can create files or folders, modify the names of files or files, and other operations.

1.2 operation

Constructor:

File(File parent, String child)
Create a new File instance based on the parent abstract pathname and the child pathname string.
File(String pathname)
Create a new File instance by converting the given pathname string to an abstract pathname.
File(String parent, String child)
Create a new File instance based on the parent pathname string and the child pathname string.
File(URI uri)
Create a new File instance by converting the given file: URI to an abstract pathname.

Common methods:

  • createNewFile(): used to create a file
  • delete(): deletes a file
  • exists(): determines whether the file exists. If it exists, it returns true. If it does not exist, it returns false
  • mkdir(): used to create single-layer folders
  • mkdirs(): used to create multi tier folders
  • If it is a folder, it will return isDirectory(): true
  • listFiles(): returns all File objects under the current folder. The returned result is a File [] type
  • getAbsolutePath(): get the absolute path of the current file
  • getName(): returns the name of the file or folder itself
  • getParent(): returns the name of the upper level directory:
  • getParentFile(): returns the File object of the upper level directory
  • isHidden(): judge whether this file is hidden
  • lastModified(): returns the last modified time of the file in milliseconds
  • length(): returns the length of the file, that is, the number of bytes
public static void main(String[] args) throws IOException {
        File file = new File("E:"+File.separator+"hello.txt");//Use system name separator
        file.createNewFile();
        //file.delete();// The files in this way are deleted directly and will not be returned to the recycle bin
        File file1 = new File("E:\\ha\\ha\\ha");
        file1.mkdirs();
        file.getName().endsWith(".txt");
        File[] files = File.listRoots();
        for (File f:files){
            System.out.println("hello");
            System.out.println(f.toString());
        }
        System.out.println("ok");
    }

2, Byte stream

####The difference between character stream and byte stream:

‚Äč 1. Byte stream can operate on any type of data, while character stream can only operate on character type data.
2. Byte stream directly operates on files and does not use buffers. The character stream uses a buffer. First, the data is written or read into the buffer, and then the data is written to a file or read into a program.

2.1 OutputStream output stream

#####2.1.1 general

Byte stream: used to send out byte type data, such as binary data such as picture, sound and video.

**Byte output stream: * * OutputStream is defined as an abstract class, which means that we cannot directly use OutputStream to create byte output stream objects. Byte output stream can not only output byte type data, but also output character type data. It only needs to convert characters into bytes.

Note: when using the input stream, if the file does not exist, a file not found exception will appear. When using the output stream, even if the file does not exist, there will be no exception, and the file will be automatically created (but if the file exists, but it is a directory rather than a regular file; or the file does not exist, but it cannot be created; or it cannot be opened for some other reason, FileNotFoundException will also be thrown).
When we use the output stream, if there is no name to specify whether to overwrite, the default is the overwrite operation, and the content of the output executed later will overwrite the content of the output executed earlier.

#####2.1.2 operation

Common FileOutputStream classes

Construction method:

FileOutputStream(File file)
Creates a File output stream that writes data to the File represented by the specified File object.
FileOutputStream(File file, boolean append)
Creates a File output stream that writes data to the File represented by the specified File object. If append is true, the original File will not be overwritten
FileOutputStream(FileDescriptor fdObj)
Creates an output file stream that writes data to a specified file descriptor that represents an existing connection to an actual file in the file system.
FileOutputStream(String name)
Creates an output file stream that writes data to a file with the specified name.
FileOutputStream(String name, boolean append)
Creates an output file stream that writes data to a file with the specified name.

Common methods:

  • void close(): close the file output stream and release all system resources related to the stream.
  • void write(byte[] b): write b.length bytes from the specified byte array to the output stream of this file.
  • void write(byte[] b, int off, int len): write len bytes from the offset off in the specified byte array to the output stream of this file.
  • void write(int b): writes the specified byte to this file output stream.
 public static void main(String[] args) throws IOException {
        FileOutputStream fos  = new FileOutputStream("E:\\a.txt");
        FileOutputStream fos2  = new FileOutputStream("E:\\a.txt",true);
        fos.write(new byte[]{65,78,56});
        fos2.write(new byte[]{75,56,45});//As long as append is not set to true in the second stream, the file will be emptied and then written out
        fos.close();
        fos2.close();
        System.out.println("Operation successful");
    }

2.2 InputStream input stream

#####2.1.1 general

**Byte input stream: * * InputStream is defined as an abstract class, which means that we cannot directly use InputStream to create the object of byte input stream. Byte input stream can not only read byte type data, but also read character type, but only need to convert characters into bytes.

#####2.1.2 operation

Common FileInputStream classes

Construction method:

FileInputStream(File file)
Create a FileInputStream by opening a connection to the actual file, which is specified by the file object file in the file system.
FileInputStream(FileDescriptor fdObj)
Create a FileInputStream by using the file descriptor fdObj, which represents an existing connection to an actual file in the file system.
FileInputStream(String name)
Create a FileInputStream by opening a connection to the actual file, which is specified by the pathname name in the file system.

Common methods:

  • void close(): close this file input stream and release all system resources related to this stream.
  • int read(): reads a data byte from this input stream.
  • Returns a byte read in. If it reaches the end of the file, - 1.
  • int read(byte[] b): read up to b.length bytes of data into a byte array from this input stream.
  • Returns the total number of bytes read into the buffer. If there is no more data because the end of the file has been reached, - 1.
  • int read(byte[] b, int off, int len): read up to len bytes of data into a byte array from this input stream.
  • long skip(long n): skip and discard n bytes of data from the input stream.
	   FileInputStream fis2 = new FileInputStream("E:\\a.txt");
        while(true){
            byte b1 = (byte)fis2.read();
            if(b1 == -1){
                break;
            }
            System.out.println((char)b1);
        }
        fis2.close();// Remember to close the flow

####2.3 encryption and decryption of documents

3.3.1 principle: in the first step, the byte input stream is used to read the file, and in the second step, the byte output stream is used to generate the encrypted file

3.3.2 simple implementation idea: any data XOR (^) operation is the original data after twice.

3.3.3 Code:

	public static void main(String[] args) throws IOException {
        File oldFile = new File("C:\\Users\\sir\\Desktop","List1.txt");
        File newFile = new File("C:\\Users\\sir\\Desktop","List2.txt");
        encryption(oldFile,newFile);
        System.out.println("Operation successful");
    }
    //Encryption or decryption method
    private static void encryption(File oldFile,File newFile) throws IOException {
        FileInputStream fis = new FileInputStream(oldFile);
        FileOutputStream fos = new FileOutputStream(newFile);
        while(true){
            int len = fis.read();
            if (len==-1) break;
            fos.write(len^10);
        }
    }

3, Character stream

3.1 Writer output stream

3.1.1 general

**Character output stream: * * character input stream can only output character data.

3.1.2 operation

Common FileReader classes

Construction method:

FileWriter(File file)
Construct a FileWriter object according to the given File object.
FileWriter(File file, boolean append)
Construct a FileWriter object according to the given File object.
FileWriter(FileDescriptor fd)
Construct a FileWriter object associated with a file descriptor.
FileWriter(String fileName)
Construct a FileWriter object according to the given file name.
FileWriter(String fileName, boolean append)
The FileWriter object is constructed based on the given file name and a boolean value indicating whether to attach write data.

Common methods:

  • void close(): close this stream, but refresh it first.
  • void flush(): flush the buffer of the stream.
  • String getEncoding(): returns the name of the character encoding used by this stream.
  • void write(char[] cbuf, int off, int len): write a part of the character array.
  • void write(int c): write a single character.
  • void write(String str, int off, int len): write a part of the string.
	public static void main(String[] args) throws IOException {
        FileWriter fw = new FileWriter("E://b.txt");
        fw.write('a');
        //When the stream is not closed, the character stream will not write the characters in the buffer to the file. You can refresh it with flush
        //fw.flush();
        //The append method is called the append method. It refers to the object it returns calling it, so it can be appended continuously
            //Whether to append in the file or whether to specify the append parameter as true when instantiating the output stream object.
        fw.append("Hoe standing grain gradually pawning a midday").append(",").append("Sweat drops under the grass");//
        fw.close();
    }

####3.2 Reader input stream

3.2.1 general

**Character input stream: * * character input stream can only read character data.

3.2.2 operation

Common FileReader classes

Construction method:

FileReader(File file)
Create a new FileReader given the File from which to read data.
FileReader(FileDescriptor fd)
Create a new FileReader given the FileDescriptor from which to read data.
FileReader(String fileName)
Create a new FileReader given the file name from which to read data.

Common methods:

  • void close(): close the stream and release all resources associated with it.
  • Single character read().
  • int read(char[] cbuf, int offset, int length): read characters into a part of the array.
  • boolean ready(): judge whether the stream is ready for reading.

4, Conversion flow

####4.1 InputStreamReader

4.1.1 overview

Byte character input

4.2 OutputStreamWriter

4.2.1 general

Byte character output

4.3 case: converting file code set

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 flow object
    	// 2.1 convert input stream and specify GBK code
        InputStreamReader isr = new InputStreamReader(new FileInputStream(srcFile) , "GBK");
    	// 2.2 convert output stream, default utf8 encoding
        OutputStreamWriter 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();
  	}
}

5, Print stream

5.1 PrintStream & PrintWriter

5.1.1 PrintStream: byte print stream

Construction method:

PrintStream(File file)
Creates a new print stream with the specified file without automatic line refresh.
PrintStream(File file, String csn)
Creates a new print stream with the specified file name and character set without automatic line refresh.
PrintStream(OutputStream out)
Create a new print stream.
PrintStream(OutputStream out, boolean autoFlush)
Create a new print stream.
PrintStream(OutputStream out, boolean autoFlush, String encoding)
Create a new print stream.
PrintStream(String fileName)
Creates a new print stream with the specified file name without automatic line refresh.
PrintStream(String fileName, String csn)
Creates a new print stream with the specified file name and character set without automatic line refresh.

Common methods:

  • void println(): terminate the current line by writing in the line separator string.
  • void println(boolean x): print the boolean value and terminate the line.
  • void println(int x): prints an integer and terminates the line
  • void close(): close the flow.
  • void flush(): flush the buffer of the stream.

#####5.1.2 PrintWriter: character print stream

Construction method:

PrintStream(File file)
Creates a new print stream with the specified file without automatic line refresh.
PrintStream(File file, String csn)
Creates a new print stream with the specified file name and character set without automatic line refresh.
PrintStream(OutputStream out)
Create a new print stream.
PrintStream(OutputStream out, boolean autoFlush)
Create a new print stream.
PrintStream(OutputStream out, boolean autoFlush, String encoding)
Create a new print stream.
PrintStream(String fileName)
Creates a new print stream with the specified file name without automatic line refresh.
PrintStream(String fileName, String csn)
Creates a new print stream with the specified file name and character set without automatic line refresh.

Common methods:

ditto

5.2 PrintWriter as conversion stream

5.2.1 general

Transfer the byte or character output to the print stream, so that the original content of the file is not overwritten

    FileOutputStream fos = new FileOutputStream("E:\\c.txt",true);//Set append to true to ensure that the original file is not overwritten
    //FileWriter fw = new FileWriter("E:\\c.txt");
    PrintWriter pw1 = new PrintWriter(fos);
    pw1.println("Hey, hey, hey");
    pw1.println("Hey, hey, hey");
    pw1.println("Hey, hey, hey");
    pw1.flush();
    pw1.close();

5.3 collect exception logs

Principle: create a print stream object and pass it as a parameter to the printStackTrace method of the exception class instance.

public static void main(String[] args) throws FileNotFoundException {
        try {
            String s = null;
            s.toString();
        }catch (Exception e){
            /*
            First create a byte output stream instance with, and the append parameter of the construction method of this byte output stream is specified as true, so that each run will not overwrite the previous information.
             */
            FileOutputStream fos = new FileOutputStream("E:\\bug.txt",true);
            PrintWriter pw = new PrintWriter(fos);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            pw.println(sdf.format(new Date()));
            e.printStackTrace(pw);
            pw.close();
        }
    }

6, Properties profile class

####6.1 Properties class and properties file

Properties: it is mainly used to produce configuration files and read the information of configuration files. Container class (belonging to map system). It represents a set of persistent properties. Properties can be saved to or loaded from a stream. Each key in the attribute list and its corresponding value is a string.

properties file: it is a configuration file, which is mainly used to express configuration information. The file type is * properties, the format is a text file, and the content of the file is in the format of "key = value".

6.2 operation

Construction method:

  • Properties() creates an empty list of properties without default values.
  • Properties(Properties defaults) creates an empty list of properties with a specified default value.

Common methods:

  • void setProperty(String key, String value) calls the put method of Hashtable, and the key value pair is stored in the hash table
  • String getProperty(String key) gets the value according to the key
  • viod load(Reader reader) reads key value pairs from the input stream
  • void list(PrintWriter out) prints the attribute list to the specified print stream
  • Void store (writer, writer, string comments) loads key value pairs into the output stream (unlike the list method, it is used to output to the configuration file)
  • Set stringPropertyNames() gets a set of keys

Because Properties inherit from Hashtable, you can apply put and putAll methods to the Properties object. But = = these two methods are not recommended because they allow the caller to insert items whose key or value is not String. Instead, use the setProperty method== If the store or save method is called on an "unsafe" Properties object (that is, a key or value that contains a non String), the call will fail. Similarly, if the propertyNames or list method is called on an "unsafe" Properties object (that is, a key that contains a non String), the call will fail.

public static void main(String[] args) throws IOException {
        /*
        //Storage file
        Properties ppt = new Properties();
        ppt.put("Java","Getting started ");
        ppt.put("C++","OK ");
        ppt.put("Python","Bad ");
        ppt.setProperty("Go","Cowhide ");
        FileWriter fw = new FileWriter("E:\\book.properties");
        ppt.store(fw,"Stored books ");
        fw.close();*/
        //read file
        Properties ppt = new Properties();
        Reader r = new FileReader("E:\\Book.properties");
        ppt.load(r);
        r.close();
        Set<String> keys = ppt.stringPropertyNames();
        for(String key:keys){
            System.out.println(key+"->"+ppt.getProperty(key));
        }
    }

7, Serialization technology

7.1 general

Serialization and deserialization is to convert objects and byte streams into each other

####7.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): create an ObjectOutputStream that specifies the OutputStream.

Construction example, 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 be implemented in 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 an attribute does not need to be serializable, the attribute 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 method

  • 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"); // The name and address are serialized, but the age is not serialized.
        } catch(IOException i)   {
            i.printStackTrace();
        }
   	}
}
Output result:
Serialized data is saved

####7.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 the 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 this 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 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.

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);
     }
}

8, Try with resources

Operation of closing flow

jdk1. At 7:

try(FileReader fr = new FileReader("E:\\c.txt")){
            int c = fr.read();
            System.out.println((char)c);
        }catch (IOException e){
            e.printStackTrace();
        }

jdk9 is optimized:

FileReader fr = new FileReader("E:\\c.txt");
PrintWriter pw = new PrintWriter("E:\\d.txt");
try(fr;pw){
    int c = fr.read();
    System.out.println((char)c);
}catch (IOException e){
    e.printStackTrace();
}

9, Buffer stream

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

Construction example, 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("jdk9.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("jdk9.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 to make it 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("jdk9.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

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

Construction example, 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("hello");
      	// Write line breaks
        bw.newLine();
        bw.write("program");
        bw.newLine();
        bw.write("member");
        bw.newLine();
		// Release resources
        bw.close();
    }
}
Output effect:
hello
 program
 member

####1.4 exercise: text sorting

Please restore the text information in order.

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. I was foolish to think that there are no big or small matters in the palace. I learned it and consulted it, and then implemented it. It will be beneficial to 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 yourself, so as to help you understand the good way, observe and accept the 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 what is good or bad.
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 former Emperor didn't treat his ministers as despicable and self defeating. He took care of his ministers in the cottage three times and consulted his ministers on the affairs of the world. Therefore, he was grateful, so he allowed the former 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 set the Central Plains. The common people are exhausted and dull, eliminate the evils, revive the Han Dynasty, and return to the old capital. Therefore, this minister is 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.

#####Case analysis

  1. Read text information line by line.
  2. Parse text information into the collection.
  3. Traverse the set 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();

        // Traverse 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 spliced text
            bw.write(key+"."+value);
          	// Write line breaks
            bw.newLine();
        }
		// Release resources
        bw.close();
    }
}

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();

    // Traverse 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 spliced text
        bw.write(key+"."+value);
      	// Write line breaks
        bw.newLine();
    }
	// Release resources
    bw.close();
}

}

































Tags: Java

Posted by irandoct on Sat, 07 May 2022 08:39:12 +0300