複製資料夾的java程式碼實現
阿新 • • 發佈:2019-02-17
package aaa; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class DEmo14 { public static void main(String[] args) { String srcaddress = "D:\\java226期"; File srcFile = new File(srcaddress); String destaddress = "E:\\a"; File destFile = new File(destaddress); destFile.mkdirs(); copyFile(srcFile,destFile); } private static void copyFile(File srcFile,File destFile) { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { File[] f = srcFile.listFiles(); for (File f1 : f) { File f2 = new File(srcFile,f1.getName()); System.out.println(f2.getName()); File f3 = new File(destFile,f1.getName()); if(f1.isFile()){ bis = new BufferedInputStream(new FileInputStream(f2)); bos = new BufferedOutputStream(new FileOutputStream(f3)); byte[] bytes = new byte[1024]; int len = 0; while((len = bis.read(bytes)) != -1){ bos.write(bytes,0,len); bos.flush(); } } else{ f3.mkdir(); copyFile(f2,f3); } } } catch (IOException e) { e.printStackTrace(); }finally{ if(bos != null){ try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if(bis != null){ try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } } }