首先我先用utf-8编码,创建一个文件,键盘输入:大家好
import java.io.* ;
class WriterDemo {
public static void main(String args[]) throws Exception{
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)) ;
FileOutputStream fos = new FileOutputStream("abc.txt") ;
OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8") ;
BufferedWriter bufw = new BufferedWriter(osw) ;
String line = null ;
while((line=bufr.readLine())!=null){
if(line.equals("over"))
break;
bufw.write(line) ;
bufw.newLine() ;
}
bufr.close() ;
bufw.close() ;
}
}
然后在写一个读取文件的代码:
import java.io.* ;
class ReaderDemo {
public static void main(String args[]) throws Exception{
FileReader fr = new FileReader("abc.txt") ;
BufferedReader bufr = new BufferedReader(fr) ;
BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(System.out,"utf-8")) ;
String line = null ;
while((line=bufr.readLine())!=null){
bufw.write(line) ;
}
bufr.close() ;
bufw.close() ;
}
}
同样是使用utf-8编码读取出来的却不是:大家好 为什么呢。我的输出是:芥径褍顔嶆總锟
出现了乱码?使用同样的编码写和读却不一样,怎么回事? |
|