簡單的 io流檔案複製(字元流編碼亂碼轉換)
阿新 • • 發佈:2019-01-01
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(); } }