標籤:color stat try sep targe port i++ stream main
1 /* 2 將"C:\\JavaProducts\\Source"下的所有資料複製到"C:\\Target"下 3 */ 4 5 import java.io.*; 6 7 public class JavaCopyDemo{ 8 final static String SOURCESTRING = "C:\\JavaProducts\\Source"; 9 final static String TARGETSTRING = "C:\\Target";10 11 public static void main(String[] args){12 if(!(new File(SOURCESTRING)).exists()){13 System.out.println("源檔案" + SOURCESTRING + "不存在,無法複製!");14 return;15 }else if((new File(TARGETSTRING)).exists()){16 System.out.println("目標檔案" + TARGETSTRING + "已經存在,無法複製!");17 return;18 }else{19 if((new File(SOURCESTRING)).isFile()){20 copyFile(new File(SOURCESTRING),new File(TARGETSTRING));21 }else if((new File(SOURCESTRING)).isDirectory()){22 copyDirectory(SOURCESTRING,TARGETSTRING);23 }24 }25 }26 27 private static void copyFile(File sourceFile,File targetFile){28 if(!sourceFile.canRead()){29 System.out.println("源檔案" + sourceFile.getAbsolutePath() + "不可讀,無法複製!");30 return;31 }else{32 System.out.println("開始複製檔案" + sourceFile.getAbsolutePath() + "到" + targetFile.getAbsolutePath());33 FileInputStream fis = null;34 BufferedInputStream bis = null;35 FileOutputStream fos = null;36 BufferedOutputStream bos = null;37 38 try{39 fis = new FileInputStream(sourceFile);40 bis = new BufferedInputStream(fis);41 fos = new FileOutputStream(targetFile);42 bos = new BufferedOutputStream(fos);43 int len = 0;44 while((len = bis.read()) != -1){45 bos.write(len); 46 }47 bos.flush();48 49 }catch(FileNotFoundException e){50 e.printStackTrace(); 51 }catch(IOException e){52 e.printStackTrace();53 }finally{54 try{55 if(fis != null){56 fis.close(); 57 }58 if(bis != null){59 bis.close(); 60 }61 if(fos != null){62 fos.close(); 63 }64 if(bos != null){65 bos.close(); 66 }67 System.out.println("檔案" + sourceFile.getAbsolutePath() + "複製到" + targetFile.getAbsolutePath() + "完成");68 }catch(IOException e){69 e.printStackTrace();70 }71 }72 }73 }74 75 private static void copyDirectory(String sourcePathString,String targetPathString){76 if(!new File(sourcePathString).canRead()){77 System.out.println("源檔案夾" + sourcePathString + "不可讀,無法複製!");78 return;79 }else{80 (new File(targetPathString)).mkdirs();81 System.out.println("開始複製檔案夾" + sourcePathString + "到" + targetPathString);82 File[] files = new File(sourcePathString).listFiles();83 for(int i = 0; i < files.length; i++){84 if(files[i].isFile()){85 copyFile(new File(sourcePathString + File.separator + files[i].getName()),new File(targetPathString + File.separator + files[i].getName())); 86 }else if(files[i].isDirectory()){87 copyDirectory(sourcePathString + File.separator + files[i].getName(),targetPathString + File.separator + files[i].getName());88 } 89 }90 System.out.println("複製檔案夾" + sourcePathString + "到" + targetPathString + "結束");91 }92 }93 }
Java將一個目錄下的所有資料複製到另一個目錄下