java将一个目录下的所有数据复制到另一个目录下
本文实例为大家分享了java将一个目录下的所有数据复制到另一个目录下的具体代码,供大家参考,具体内容如下
/* 将"C:\\JavaProducts\\Source"下的所有数据复制到"C:\\Target"下 */ importjava.io.*; publicclassJavaCopyDemo{ finalstaticStringSOURCESTRING="C:\\JavaProducts\\Source"; finalstaticStringTARGETSTRING="C:\\Target"; publicstaticvoidmain(String[]args){ if(!(newFile(SOURCESTRING)).exists()){ System.out.println("源文件"+SOURCESTRING+"不存在,无法复制!"); return; }elseif((newFile(TARGETSTRING)).exists()){ System.out.println("目标文件"+TARGETSTRING+"已经存在,无法复制!"); return; }else{ if((newFile(SOURCESTRING)).isFile()){ copyFile(newFile(SOURCESTRING),newFile(TARGETSTRING)); }elseif((newFile(SOURCESTRING)).isDirectory()){ copyDirectory(SOURCESTRING,TARGETSTRING); } } } privatestaticvoidcopyFile(FilesourceFile,FiletargetFile){ if(!sourceFile.canRead()){ System.out.println("源文件"+sourceFile.getAbsolutePath()+"不可读,无法复制!"); return; }else{ System.out.println("开始复制文件"+sourceFile.getAbsolutePath()+"到"+targetFile.getAbsolutePath()); FileInputStreamfis=null; BufferedInputStreambis=null; FileOutputStreamfos=null; BufferedOutputStreambos=null; try{ fis=newFileInputStream(sourceFile); bis=newBufferedInputStream(fis); fos=newFileOutputStream(targetFile); bos=newBufferedOutputStream(fos); intlen=0; while((len=bis.read())!=-1){ bos.write(len); } bos.flush(); }catch(FileNotFoundExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); }finally{ try{ if(fis!=null){ fis.close(); } if(bis!=null){ bis.close(); } if(fos!=null){ fos.close(); } if(bos!=null){ bos.close(); } System.out.println("文件"+sourceFile.getAbsolutePath()+"复制到"+targetFile.getAbsolutePath()+"完成"); }catch(IOExceptione){ e.printStackTrace(); } } } } privatestaticvoidcopyDirectory(StringsourcePathString,StringtargetPathString){ if(!newFile(sourcePathString).canRead()){ System.out.println("源文件夹"+sourcePathString+"不可读,无法复制!"); return; }else{ (newFile(targetPathString)).mkdirs(); System.out.println("开始复制文件夹"+sourcePathString+"到"+targetPathString); File[]files=newFile(sourcePathString).listFiles(); for(inti=0;i以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。