ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.nio.channels.FileChannel;Importjava.util.ArrayList;Importjava.util.List;/*** File copy *@authorLixiaolong*/ Public classFiletransfer {/*** A copy of the entire directory/subdirectory/file using the Channel method *@throwsIOException*/ Public voidUsechannel ()throwsIOException {String driver= "F:\\agilecontroller"; String Path= "/tomcat/webapps/opmui/customize"; File input=NewFile (Driver +path); String Bakpath= "\\syncbak"; File Bakfile=NewFile (Driver +Bakpath); if(Bakfile.exists ()) {DeleteFile (bakfile); } bakfile.mkdirs (); File Output=NewFile (Driver + Bakpath +path); if(Input.isdirectory ()) {output.mkdirs (); List<File> allfilelist =NewArraylist<file>(); Getallfiles (input, allfilelist); for(File f:allfilelist) {String OutputPath=F.getcanonicalpath (); if(Outputpath.startswith (Driver)) {OutputPath= driver + Bakpath +outputpath.substring (Driver.length (), outputpath.length ()); } Output=NewFile (OutputPath); if(F.isdirectory ()) {output.mkdirs (); } Else{fileCopy (f, Output); } } } Else{fileCopy (input, output); } } /*** Recursively list all subdirectories/files *@paramDirectory *@paramallfilelist*/ Private voidGetallfiles (File directory, list<file>allfilelist) {File flist[]=Directory.listfiles (); if(Flist = =NULL|| Flist.length = = 0) { return; } for(File f:flist) {if(F.isdirectory ()) {//List all sub-foldersAllfilelist.add (f); Getallfiles (f, allfilelist); } Else { //List all FilesAllfilelist.add (f); } } } /*** Copy a single file using the Channel method *@paramInput *@paramOutput *@throwsIOException*/ Private voidFileCopy (file input, file output)throwsIOException {if(!input.exists ()) { return; } if(!output.exists ()) {Output.createnewfile (); } FileInputStream FIS=NewFileInputStream (input); FileOutputStream Fos=Newfileoutputstream (output); FileChannel Inputchannel=NULL; FileChannel Outputchannel=NULL; Try{Inputchannel=Fis.getchannel (); Outputchannel=Fos.getchannel (); Outputchannel.transferfrom (Inputchannel,0, Inputchannel.size ()); } finally{inputchannel.close (); Outputchannel.close (); Fis.close (); Fos.close (); } } /*** Cascade Delete Files *@paramfile*/ Private voiddeletefile (file file) {if(File.isdirectory ()) {file[] files=File.listfiles (); for(File f:files) {f.delete (); }} file.delete (); } Public Static voidMain (string[] args) {filetransfer ft=NewFiletransfer (); Try{Ft.usechannel (); } Catch(IOException e) {System.out.println (e); } System.out.println ("End"); }}
Java copy directory/subdirectory/file