Conversion flow:
Commutations provides conversion between a byte stream and a stream of characters for reading the byte stream is converted into the character stream read, write the converted character stream is a stream of bytes to write, including InputStreamReader and OutputStreamWriter, in which:
- InputStreamReader: convert the InputStream Reader, it has two types of construction methods:
- public InputStreamReader (InputStream in): The system default character set
- public InputSreamReader (InputStream in, String charsetName): specify the character set
- OutputStreamWriter: Writer will convert OutputStream, it also has two types of construction methods:
- public OutputStreamWriter (OutputStream out): The system default character set
- public OutputStreamWriter(OutputStream out,String charsetName):指定字符集
Example: "Hello.txt" print file in the console, and stores in gbk encoding format "Hello-gbk.txt" file
package cn.jingpengchong.io;
import java.io.*;
public class Test {
public static void main(String[] args) {
String src = "Hello.txt";
String des = "Hello-gbk.txt";
test(src,des);
}
private static void test(String src, String des) {
//第二个参数为指定的字符集,如果省略了则使用系统默认的字符集,具体使用何种字符集取决于保存文件时使用的字符集
InputStreamReader reader= null;
OutputStreamWriter writer = null;
try {
reader = new InputStreamReader(new FileInputStream(src),"utf-8");
writer = new OutputStreamWriter(new FileOutputStream(des), "gbk");
char[] data = new char[10];
int read = reader.read(data);
while (read != -1){
String str = new String(data,0,read);
System.out.print(str);
writer.write(data,0,read);
read = reader.read(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(writer != null){
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Results are as follows:
At this time, if the opening "Hello-gbk.txt" file in UTF-8 format, distortion will occur: