测试代码:
/**
package com.jwen;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
* @author jwen
*
*/
public class TestFileReaderAndWriter {
public static void main(String[] args) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("e:/file.txt");
} catch (FileNotFoundException e) {
System.out.println("the file isn't found!");
return;
}
try {
fw = new FileWriter("e:/file1.txt");
} catch (IOException e) {
System.out.println("the file read or write errors !");
return;
}
int c = -1;
try {
while((c = fr.read()) != -1) {
fw.write(c); //写进文件的也可能是乱码
System.out.print((char)c); //如果你的系统不是中文的(比如英文)显示出的文字可能会是乱码
}
fw.flush();
} catch (IOException e) {
System.out.println("the file read or write errors !");
} finally {
try {
fr.close();
fw.close();
} catch (IOException e) {
System.out.println("the file close errors !");
}
}
}
}
原因:
你的文件编码默认是ANSI编码。
不同的国家和地区制定了不同的标准,由此产生了 GB2312, BIG5, JIS 等各自的编码标准。这些使用 2 个字节来代表一个字符的各种汉字延伸编码方式,称为 ANSI 编码。在简体中文系统下,ANSI 编码代表 GB2312 编码,在日文操作系统下,ANSI 编码代表 JIS 编码。
不同 ANSI 编码之间互不兼容,当信息在国际间交流时,无法将属于两种语言的文字,存储在同一段 ANSI 编码的文本中。
如果你的系统是非中文的,你的ANSI对应着相应的编码。当读取一个文件中的中文时,就会出现乱码。当然通过FileWriter写入另一个文件时,也会是乱码。(因为问题出在读取上)
解决办法:
1 通过另一个节点流FileInputStream转码。
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "GBK"); //或GB2312,GB18030
BufferedReader read = new BufferedReader(isr);