一: InputStreamReader不乱码的形式
public static void main(String[] args) throws Exception{
//这里指的UTF-8是指用从a.txt中读取字节然后通过utf-8解码成字符
InputStreamReader isr = new InputStreamReader(neM FileInputStream(name: "a.txt"),
charsetName: "utf-8");
int ch;
while (( ch=isr.read())!=-1) {
system.out.print( ( char)ch);
}
isr.close();
}
注: a.txt中存入的是"中国"两个字节,你能看到是因为txt文档翻译好了,这里a.txt是以utf-8编码格式的,所以后面解析也应该使用utf-8编码格式
InputStreameReader不乱码的读和解析原理
字符输入缓冲区中以utf-8去解析其中缓冲的字节
二: InputStreamReader中乱码问题
public static void main(String[] args) throws Exception{
InputStreamReader isr = new InputStreamReader(new FileInputStream( name: "a.txt")
, charsetName: "GBK");
int ch;
while ((ch=isr.read() )!=-1){
system.out.print((char)ch);
}
isr.close();
}
}
InputStreamReader乱码的读和解析原理
三: OutputStreamWriter
public static void main(String[] args) throws Exception {
//这里的UTF-8中指的是当把中国按UTF-8编译的字节写入b.txt,但是最后b.txt中看到的结果是什么,还要看b.txt中解码的编码是什么
outputStreamwriter osw2 = new OutputStreamMriter(new FileOutputStream name: "b.txt" ),
charsetName:"UTF-8");
osw2.write(“中国");
osw2.flush();
osw2.close();
}
OutputStreamWrite写入及其解析原理
四: 综合运用OutputStreamWriter和InputStreamReader来读写字符(其乱码的情况)
复制文件
字符流复制文本乱码因素:
4个因素: 源文件编码,Reader缓冲区编码,Writer缓冲区编码,目标文件编码,其中源文件编码和Reader缓冲区编码需要一致,Writer缓冲区编码和目标文件编码需要一致。
public staticl void main(String[] args) throws Exception{
InputStreamReader isr = new InputStreamReader( new FileInputStream( name: "a.txt" ),
charsetName: "UTF-8");
outputStreamwriter osw2 = new OutputStreamMwriter(new FileOutputStream( name: "b.txt"),
charsetiName: "UTF-8");
int ch;
while ((ch=isr.read())!=-1){
osw2.write(ch);
}
isr.close();
oSw2.close();
}
解析原理
五: OutputStreamWriter和InputStreamReader读取非文本文档所需要注意的问题.
public static void main(string[] args) throws Exception{
InputStreamReader isr = new InputStreamReader(new FileInputStream( name: "D:|[code\l1.jp&"), charsetName: "UTF-8");
OutputStreamM/riter osw2 = new OutputStreanmM/nriter(new FileOutputStream( name: "D:|[code\L2.jpn:"), charsetName: "UTF-8");
int ch;
whi1e ((ch=isr.read())!=-1){
osw2.write(ch);
}
isr.close();
osw2.close();
}
结果: 会出现图片内容增大的问题,复制的图片已经损坏了
原理解释
解决办法: 将编码格式改为iSO8859-1编码
public static void main(String[] args) throws Exception{
InputStreamReader isr = new InputStreamReader(new FileTnputStream(name: "D: [code|l1.jpeE"), charsetName: "IS0-8859-1");
OutputstreamNnriter osw2 = new Outputstream/nriter(new FileOutputstream(name: "D: \lcode\\2.jpg" ), charsetName: "Is0-8859-1");
int ch;
while ((ch=isr.read())!=-1) i
osw2.write(ch);
}
isr.close();losw2.close();
}
解析原理: 每一个字节都能在ISO8859-1中找到
拓展: Tomcat服务器中底层编码用的就是ISO8859-1来采取编码的