一、使用字符流复制纯文本文件
字符流可以读取纯文本文件,而且比字节流读取的速度要快。
实现:
1 public void copy(String srcFileName, String destFileName) throws IOException{ 2 //1、选择IO流,并创建IO流 3 FileReader fr = new FileReader(srcFileName); 4 FileWriter fw = new FileWriter(destFileName); 5 6 //2、一边读一边写 7 char[] arr = new char[1024]; 8 int len; 9 //数据从 srcFileName文件 --> fr --> arr数组 --> fw --> destFileName 10 while((len = fr.read(arr)) != -1){ 11 fw.write(arr, 0, len); 12 } 13 14 //3、关闭 15 fw.close(); 16 fr.close(); 17 18 }
二、使用字节流复制任意类型的文件
字节流可以复制任意类的文件
实现:
1 public void copy(String srcFilename , String destFilename) throws IOException{ 2 FileInputStream fis = new FileInputStream(srcFilename); 3 FileOutputStream fos = new FileOutputStream(destFilename); 4 5 byte[] arr = new byte[1024]; 6 int len; 7 //数据: srcFilename --> fis --> arr --> fos --> destFilename 8 while((len = fis.read(arr)) !=-1){ 9 fos.write(arr, 0, len); 10 } 11 12 fis.close(); 13 fos.close(); 14 }
三、使用缓冲流复制文件
缓冲流作为一个处理流,相对于上面两个方法来说,速度上更快了
实现:
1 public void copy(String srcFilename , String destFilename) throws IOException{ 2 FileInputStream fis = new FileInputStream(srcFilename); 3 BufferedInputStream bis = new BufferedInputStream(fis); 4 5 FileOutputStream fos = new FileOutputStream(destFilename); 6 BufferedOutputStream bos = new BufferedOutputStream(fos); 7 8 byte[] arr = new byte[10]; 9 int len; 10 //数据: srcFilename --> fis --> arr --> fos --> destFilename 11 while((len = bis.read(arr)) !=-1){ 12 bos.write(arr, 0, len); 13 } 14 15 bis.close(); //先关处理流 16 fis.close(); //再管节点流 17 18 bos.close(); 19 fos.close(); 20 }
来源:https://www.cnblogs.com/niujifei/p/12234621.html