1. The character set and character encoding
- Character Encoding: a natural language character binary number corresponding to the rules of
encoding: Character (can understand) -> bytes (read)
decoding: bytes (read) -> character (can read) - The character set (code table)
2. Conversion flow
- (E.g. garbled when using UTF-8 with the software reads the Windows file system default encoding GBK) conversion between different code sets will be garbled, the stream can be specified using the conversion code table: reasons for usingRead any file encoding format
- Switching principle:
2.1OutputStreamWriter
-
OutputStreamWriter
It isWriter
subclass - Construction method
OutputStreamWtiter(OutputStream out) 使用默认字符编码
OutputStreamWtiter(OutputStream out,String charsetName) 使用指定的字符编码
OutputStream out
: Byte output stream, can be used to write the write destinationString charsetName
: Encoding table name, case insensitive, UTF-8 / utf-8 (default), GBK / gbk ...- Steps for usage
- Creating
OutputStreamWriter()
the class object, method of construction and the specified output stream fill character code table - Using the
write()
method, converts the character bytes stored inBuffer - Using the
flush()
method, will refresh the data buffer to a file - Release resources
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class Demmo01 {
public static void main(String[] args) throws IOException {
FileOutputStream file = new FileOutputStream("G:\\Java\\测试文件夹\\GBK.txt");
OutputStreamWriter Osw = new OutputStreamWriter(file,"GBK");
char[] chars = {'a','b','你','好'};
Osw.write(chars);
Osw.flush();
Osw.close();
}
}
2.2InputStreamReader
-
InputStreamReader
It isReader
subclass - Construction method
InputStreamReader(InputStream in) 使用默认字符编码
InputStreamReader(InputStream in,String charsetName) 使用指定的字符编码
- Steps for usage
- Create a
InputStreamReader()
class object, constructor and fill in the character input stream designated coding table - Using the
read()
method, data is read into memory according to a specified code table - Release resources
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Demo02 {
public static void main(String[] args) throws IOException {
InputStreamReader in = new InputStreamReader(new FileInputStream("G:\\Java\\测试文件夹\\GBK.txt"), "GBK");
int len = 0;
while ((len = in.read()) != -1) {
System.out.println((char) len);
}
in.close();
}
}
Using UTF-8:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Demo02 {
public static void main(String[] args) throws IOException {
InputStreamReader in = new InputStreamReader(new FileInputStream("G:\\Java\\测试文件夹\\GBK.txt"), "UTF-8");
int len = 0;
while ((len = in.read()) != -1) {
System.out.println((char) len);
}
in.close();
}
}