1.用这两种流进行拷贝文件,会有很多小伙伴出现乱码,相信大家都知道有
转换流--InputStreamReader和OutputStreamWriter
进行转换,从而解决问题,举个例子,如下:
import java.io.*;
public class BufferedCopy_ {
public static void main(String[] args) {
//BufferedReader 和 BufferedWriter 是安装字符操作
//不要去操作二进制文件[doc, pdf, 视频, 声音],可能造成文件损坏
//拷贝
String srcFilePath = "d:\\demo\\aa.java";
String destFilePath = "d:\\demo\\bb.java";
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
String line = null;
try {
//解决乱码
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(srcFilePath), "GB2312");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(destFilePath), "GB2312");
bufferedReader = new BufferedReader(inputStreamReader);
bufferedWriter = new BufferedWriter(outputStreamWriter);
while ((line = bufferedReader.readLine()) != null){
//读取一行就写入
bufferedWriter.write(line);
bufferedWriter.newLine(); //换行
}
System.out.println("拷贝完毕");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(bufferedReader != null){
bufferedReader.close();
}
if (bufferedWriter != null){
bufferedWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
以上是很多博主的回答,但是今天我们来看一个不一样的:
2.打开你要操作的文件,点开另存为,你就会发现一个问题:
是不是发现文件的编码是ANSI(国标码,根据当前系统来确定的),这时候你只需要把ANSI改成UTF-8就可以了
如下:
3.过程演示
package com.hspedu.transformation;
import java.io.BufferedReader;
import java.io.FileReader;
public class CodeQuestion {
public static void main(String[] args) throws Exception {
String filePath = "d:\\demo\\dd.java";
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
String read;
while ((read = bufferedReader.readLine()) != null){
System.out.print(read + "\n");
}
bufferedReader.close();
}
}
看此时控制台结果:
当我们将编码改变时候,控制台结果:
希望可以帮助到大家!