public static voidmain(String args[]) {
FileInputStream fis =null;
FileOutputStream fox =null;
OutputStreamWriter osw =null;
InputStreamReader inputStreamReader =null;
try{
fis =newFileInputStream("F:\\a.txt");
/** 前提:当您要write数据时,要先确保read的数据不是乱码的,不然write后的数据怎么该编码格式都会是乱码的,因为它的本质已经是乱码的了
*因为我的IDEA的默认编码是UTF-8
,所以inputStreamReader的编码也是UTF-8;而记事本的编码是ANSI,
*即是系统默认编码GBK,所以要指定GBK的编码格式读取 ,而如果您的编辑器默认的编码格式是GBK,那么不指定编码格式也不会乱码
*/
inputStreamReader =newInputStreamReader(fis,"GBK");
fox =newFileOutputStream("F:\\b.txt");
osw =newOutputStreamWriter(fox,"GBK");
char[] bytes =new char[64]; //因为inputStreamReader读取的是字符数组,而如果读取的是字节数组,才会构建一个字节数组
while((inputStreamReader.read() != -1)) {
intread = inputStreamReader.read(bytes);
osw.write(newString(bytes,0,read)); //将字符数组转成字符串,进而write字符数据
System.out.println(newString(bytes,0,read));
osw.flush();//要刷新,不然输出不了文字
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}finally{
try{
inputStreamReader.close();
//资源关闭原则,先开后关(前提这些资源有关联性)
osw.close();
fox.close();
fis.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}

592

被折叠的 条评论
为什么被折叠?



