JAVA学习日志:cmd里文件读出中文乱码
我碰到一个乱码问题,废话不多说,先上代码:
public class MainClass {
public static List<String> read(String filename) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(filename)) ;
String s ;
List<String> result = new ArrayList<String>() ;
while((s = in.readLine()) != null) {
result.add(s) ;
}
in.close() ;
return result ;
}
public static void write(String fromname , String toname) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(fromname)) ;
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(toname))) ;
String s ;
while((s = in.readLine()) != null ) {
out.println(s) ;
}
in.close() ;
out.close() ;
}
public static void main(String[] args) throws IOException {
String from = "from.txt" , to = "to.txt" ;
write(from , to) ;
List<String> ls = read(to) ;
for(ListIterator<String> it = ls.listIterator() ; it.hasNext() ; ) {
print(it.next()) ;
}
}
}
我使用上面的代码中的write方法,把from.txt中的文件复制到to.txt文件中,再利用read方法读出文件to中的内容。然而…
错误原因:cmd,记事本的中文编码方式不一样:
在cmd输入chcp
C:\Users\26973\Desktop\java\chapter18\MyFirstFileIO>chcp
活动代码页: 936
输入 chcp 65001
C:\Users\26973\Desktop\java\chapter18\MyFirstFileIO>java MainClass
这是?段中文代?
这是?段中文代?
这是?段中文代?
这是?段中文代?
这是?段中文代?
这是?段中文代?
这是?段中文代?
这是?段中文代?
这是?段中文代?
这是?段中文代?
大部分中文修复了,还是有一些乱码。