InputStreamReader/OutputStreamWriter乱码问题解决
/*
*InputStreamReader参数charset要跟文件编码格式一致。 InputStreamReader读的时候才不会乱码。
*OutputStreamWriter参数charset设置编码例如UTF-8。在操作系统打开文件时候也要用相应编码打开才不会乱码。
*InputStreamReader:读操作时编码要与文件编码一致。OutputStreamWriter写操作时设置编码打开文件时也要以相同编码打开。
*/
public class Test{
/*记事本读写
*写字板编码转化为UTF-8的方式非常简单,用记事本打开文件,文件->另存为->在编码中选择uft-8保存就可以了。
*注意:666.txt和999.txt文件编码都要是UTF-8编码才能保证读写不会乱码。
*/
public static void main(String[] args) throws IOException {
Reader reader = new InputStreamReader(new FileInputStream(new File("e:/666.txt")),"UTF-8");
Writer writer = new OutputStreamWriter(new FileOutputStream(new File("e:/999.txt")),"UTF-8");
char[] buffer = new char[1024];
int len = 0;
while((len=reader.read(buffer))!= -1){
System.out.println(new String(buffer,0,len));
writer.write(buffer, 0, len);
}
writer.flush();
writer.close();
}
/*word读写*/
public static void main(String[] args) throws IOException {
Reader reader = new InputStreamReader(new FileInputStream(new File("e:/123.doc")),"utf-8");
Writer writer = new OutputStreamWriter(new FileOutputStream(new File("e:/456.doc")),"utf-8");
char[] buffer = new char[1024];
int len = 0;
while((len=reader.read(buffer))!= -1){
System.out.println(new String(buffer,0,len));
writer.write(new String(buffer,0,len));
}
writer.flush();
writer.close();
}
/*
*创建记事本999.txt
*OutputStreamWriter(FileOutputStream,charset)以UTF-8编码写出,正确写法。
*问题导致原因:999.txt默认以写字板方式打开就乱码,写字板打开打开的时候解码解错,以UTF-8打开问题解决或者换高级编辑器打开。
*/
public static void main(String[] args) throws IOException {
String file = "e:\\999.txt";
String charset = "UTF-8";
FileOutputStream outputStream = new FileOutputStream(file);
Writer writer = new OutputStreamWriter(outputStream, charset);
try {
writer.write("字符流写乱码。。。");
} finally {
writer.close();
}
}
}
感谢您的阅读,您的支持是我写博客动力。