使用字节流文件复制
public class CopyTest01 { public static void main(String[] args) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream("C:\\Users\\王一林\\Desktop\\论文pdf\\2122_41_13500_080902_3118070108_BS_001.pdf"); fos = new FileOutputStream("D:\\2122_41_13500_080902_3118070108_BS_001.pdf"); //先读,每次读1M数据(1024 * 1024)// 最核心的:一边读,一边写 byte[] bytes = new byte[1024 * 1024]; int readCount = 0; while((readCount = fis.read(bytes)) != -1){ //读多少,就写多少API fos.write(bytes,0,readCount); } //最后输出流一定要刷新 fos.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { //这里要分开try,因为如果一起try的话,如果其中一个流出现异常会影响到另一个流的关闭。 if(fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if(fos != null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
复制结果
使用FileReader FileWriter字符流进行拷贝的话,只能拷贝“普通文本”文件。(.java文件也是普通文本文件)
public class Copy02Test01 { public static void main(String[] args) { FileReader in = null; FileWriter out = null; try { in = new FileReader("IO\\src\\com\\newstudy\\javase\\io\\Copy02Test01.java"); out = new FileWriter("Copy02Test01.java"); //读,每次读1MB char[] chars = new char[1024 * 512];//1MB int readCount = 0; //一边读,一边写 while((readCount = in.read(chars)) != -1){ //写 out.write(chars,0,readCount); } //刷新 out.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(in != null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if(out != null){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
复制结果