First, the theory:
1. What is the difference between character stream and byte stream?
Character stream = byte stream + encoding set, in the actual reading of the character stream or byte to read, but will be more encoded set to find the encoding set dictionary to parse the corresponding byte, so that one read a character;
2. What is a conversion stream?
The conversion stream is originally a byte stream, but the data read is a character, so we want to use a character stream to operate, then you can use the conversion stream to convert;
Convert stream = byte stream + encoding set.
The conversion stream is characterized by the ability to specify an encoding set.
3, the role of the conversion stream:
(1), read the data input from the console (keyboard input), write them to the file (we write the character bar);
(2), when the file parsing, if involved in coding, you need to use the conversion stream to decode--------garbled is not fun.
Second, the actual combat:
1. Save text from keyboard input to file:
Try (inputstreamreader Inreader = new InputStreamReader (system.in)) { StringBuilder sb = new StringBuilder (); int ch; Try (outputstream out = new FileOutputStream ("Console.txt")) {while ((ch = inreader.read ())! =-1) { if (char) c h = = ' \ r ') continue; if (char) ch = = ' \ n ') { System.out.println (sb.tostring (). toUpperCase ()); Out.write (Sb.tostring (). GetBytes ()); Sb.delete (0, Sb.length ()); Continue; } Sb.append ((char) ch); if (sb.tostring (). Equals ("ESC")) Break;}}}
1), we often use the System.out.println is the input stream, natural, and it corresponds to the input stream, the input is the keyboard, the output of the object is to the console;
2. Encoding and decoding:
Try (BufferedReader INREADERGBK = new BufferedReader (new InputStreamReader (New FileInputStream ("Gbk.txt"), "GBK")) { C1/>try (BufferedWriter outWriterUTF8 = new BufferedWriter (New OutputStreamWriter ("A Brief history of human beings. txt"), " Utf-8 "))) { int ch; while ((ch = inreadergbk.read ())! =-1) { outwriterutf8.write (ch);}} }
In the above code, the "Gbk.txt" file is encoded using GBK, while the "human history of". txt "file is used utf-8; we use the conversion stream to convert GBK encoded files into UTF-8 encoded formats. The principle is as follows:
1, read "Gbk.txt" time, first read the byte, and then according to our designated encoding set to find the dictionary, so you can read out the correct character;
2, while writing "A Brief history of human beings. txt" file, the word Mr. Foo is through the conversion stream, the conversion stream received the character, looked at himself was designated as the Utf-8 format, so go to the encoding set, the received character into the UTF-8 encoded format, and then write the file;
3, over.
The use and encoding and decoding principle of java-io flow