IO流案例:1.復制多級文件夾 2.刪除多級文件夾
阿新 • • 發佈:2019-04-04
exception 得到 多級 static oid while 一個 是否 調用
package copy; /* 需求:復制多級文件夾 復制d:\\itcast(包含文件和子文件夾)到模塊目錄下 分析: d:\\itcast a.txt b.txt javaweb a.xml b.xml 模塊\\itcast javaweb a.xml b.xml a.txt b.txt 思路: 1.判斷源文件是目錄還是文件 2.是目錄: 1.源目錄名+目的目錄,創建新目錄File對象 2.判斷新目錄File是否存在,不存在則創建 3.獲取源目錄文件列表 4.遍歷得到每個源文件對象 5.遞歸調用copyFolder方法 3.是文件: 復制源文件到目的目錄 */ import java.io.*; public class CopyFolder { public static void main(String[] args) throws IOException { //創建源目錄 File srcFolder = new File("d:\\itcast"); //創建目的目錄 File dstFolder = new File("day10Home"); //調用復制方法,復制目錄或文件 copyFolder(srcFolder, dstFolder); } /** * 文件是否存在的檢查工作,應該由方法調用者保證。 * @param src * @param dst * @throws IOException */ private static void copyFolder(File src, File dst) throws IOException { //1.是目錄 if(src.isDirectory()){ //1.源目錄名+目的目錄,創建新目錄File對象 File newFolder = new File(dst, src.getName()); //2.判斷新目錄File是否存在,不存在則創建 if(!newFolder.exists()) newFolder.mkdir(); //3.獲取源目錄文件列表 File[] fileArray = src.listFiles(); //4.遍歷得到每個源文件對象 for(File srcFile : fileArray){ //5.遞歸調用copyFolder方法 copyFolder(srcFile, newFolder); } }else{ // 2.是文件,根據目的目錄+源文件名,創建新文件 File newFile = new File(dst, src.getName()); copyFile(src, newFile); } } private static void copyFile(File srcFile, File newFile) throws IOException { // 創建字節緩沖流對象 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile)); // 讀寫數據,一次讀寫一個字節數組 byte[] bys = new byte[1024]; int len; while((len = bis.read(bys)) != -1){ bos.write(bys, 0, len); } // 釋放資源 bos.close(); bis.close(); } }
案例2:刪除多級文件夾
1 package deletefolder; 2 3 import java.io.File; 4 5 /* 6 需求: 7 將d:\\itcast多級文件夾刪除 8 d:\\itcast 9 javaweb 10 a.xml 11 a.txt 12 b.txt 13 思路: 14 1.是否是目錄 15 是目錄: 16 2.獲取文件列表17 3.遍歷文件列表得到每個文件對象 18 4.遞歸調用刪除方法,刪除目錄中的每一項內容 19 2.直接刪除src,此時src要麽是空目錄,要麽是文件。 20 21 */ 22 public class DeleteFolder { 23 public static void main(String[] args) { 24 //創建要刪除的多級目錄 25 File file = new File("day10Home\\itcast"); 26 27 //調用方法刪除多級目錄28 deleteFolder(file); 29 30 } 31 32 private static void deleteFolder(File src) { 33 //1.是否是目錄 34 if(src.isDirectory()){ 35 //2.獲取文件列表 36 File[] fileArray = src.listFiles(); 37 38 //3.遍歷文件列表得到每個文件對象 39 for(File file : fileArray){ 40 //4.遞歸調用刪除方法,刪除目錄中的每一項內容 41 deleteFolder(file); 42 } 43 } 44 //5.將src刪除,此時src要麽是空目錄,要麽是文件。 45 src.delete(); 46 } 47 }
IO流案例:1.復制多級文件夾 2.刪除多級文件夾