简单的 io流文件复制(字符流编码乱码转换)

时间:2021-10-11 21:00:59
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Writer;

public class Text {

public static void main(String[] args) throws IOException {

// 字节流

String file="D://test.txt";
String file2="D://test2.txt";

InputStream in = new FileInputStream(new File(file));
OutputStream out = new FileOutputStream(new File(file2));

byte[] buffer = new byte[in.available()];
while (in.read(buffer) > -1) {
out.write(buffer);
}

in.close();
out.close();


// 字符流

File fr = new File("D://test.txt");
File fw = new File("D://ccc.txt");

// File fww = new File(fw, "test.txt");
// if(!fw.exists()){ //如果不存在要复制的文件路劲
// fw.mkdirs();//创建文件路劲
// }
InputStreamReader rd = new InputStreamReader(new FileInputStream(fr),"GB2312");// 编码转码
Writer wt = new FileWriter(fw);

char[] ch = new char[1];

while (rd.read(ch) != -1) {
int len = ch.length;
wt.write(ch, 0, len);
}
rd.close();
wt.close();

}
}
简单的 io流文件复制(字符流编码乱码转换)