TestCopyDocuments.javajava
package com.sxt.parc; /* * 複製文件夾 包含文本 視頻 音頻 用字節流 */ import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; public class TestCopyDocuments { public static void main(String[] args) throws Exception { copyDocuments("G:\\source.txt","G:\\dest.txt"); } public static void copyDocuments(String SourcePath, String DestPath) throws Exception { //讀入文件到程序 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(SourcePath)); //寫入數據到文件 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(DestPath)); byte[] b = new byte[1024]; int len = 0; while((len = bis.read(b)) != -1){ bos.write(b, 0, len); } bis.close(); bos.close(); System.out.println("複製文件完成!"); } }
TestCopyFiles2.javaspa
package com.sxt.parc; /* * 文件夾以及文件的複製 */ import java.io.File; public class TestCopyFiles2 { public static void main(String[] args) throws Exception { CopyFiles("G:\\source","G:\\dest"); System.out.println("*********複製完成**************"); } private static void CopyFiles(String sourcePath, String destPath) throws Exception { //源路徑 File file = new File(sourcePath); // String name = file.getName(); // System.out.println(name); //檢查源路徑是否正確 if(!file.exists()){ System.out.println("請檢查您的源路徑是否合法!"); } //目標路徑 File file2 = new File(destPath); //若是目標文件夾不存在則建立 if(!file2.exists()){ file2.mkdir();//當前目錄建立 } // //列出源文件夾的文件和文件夾列表準備複製 // String[] list = file.list();//String類型 // for(String doc: list){ // System.out.println(doc); // } //列出源文件夾的文件和文件夾列表準備複製 File[] listFiles = file.listFiles(); for(File f :listFiles){ System.out.println(f.getName()); //若是是文件夾須要在目標文件夾下建立文件夾 if(f.isDirectory()){ //關鍵步驟:遞歸 //System.out.println(f+"--------->"+destPath+"\\"+f.getName()); CopyFiles(sourcePath+"\\"+f.getName(),destPath+"\\"+f.getName()); } //若是不是文件夾直接複製 if(f.isFile()){ //關鍵步驟:遞歸 //System.out.println(f+"--------->"+destPath+"\\"+f.getName()); TestCopyDocuments.copyDocuments(sourcePath+"\\"+f.getName(),destPath+"\\"+f.getName()); } } } }