Ways to reference notes, "Implementation of file copy"
1 Public Static voidcopydirectory (File src,file dest) {2 if(Src.isdirectory ()) {3dest=NewFile (Dest,src.getname ());//Create the SRC folder under the Dest folder4 }5 copydir (SRC, dest);6 }7 Public Static voidcopydir (File src,file dest) {8 9 if(Src.isdirectory ()) {Ten dest.mkdirs (); One for(File sub:src.listFiles ()) { ACopyDirectory (Sub,NewFile (Dest,sub.getname ())); - } -}Else if(Src.isfile ()) { the copyFile (SRC, dest); - } -}
A (source folder) B (destination folder) / \b C |D.txtSuppose at this point, to copy the A folder to the B folder1. What does the Copydir () method do for you? A : In order to copy a (folder), it is only used to copy a, do not include a folder inside the B/c/d.txt and other files. if Copydir () is not called, then the contents of the B folder will be:B / \b C |D.txtthe result of calling Copydir () is: B |A / \b C |D.txtFull code:
1 Packagecom. IO;2 ImportJava.io.*;3 Public classCopyutil {4 /**5 * Copy Folder6 * @paramsrc7 * @paramdest8 */9 Public Static voidCopyDirectory (String srcpath,string destpath) {//overloaded CopyDirectory () methodTenFile src=NewFile (srcpath); OneFile dest=NewFile (destpath); A copydirectory (SRC, dest); - } - Public Static voidcopydirectory (File src,file dest) { the if(Src.isdirectory ()) { -dest=NewFile (Dest,src.getname ());//create a file with the same name as SRC under the dest directory - } - copydir (SRC, dest); + } - Public Static voidcopydir (File src,file dest) { + if(Src.isdirectory ()) { A dest.mkdirs (); at for(File file:src.listFiles ()) { -Copydir (file,NewFile (Dest,file.getname ()));//Focus!! - } -}Else if(Src.isfile ()) { - copyFile (SRC, dest); - } in } - /** to * Copy Files + * @paramsrc - * @paramdest the */ * Public Static voidcopyFile (String srcpath,string destpath) { $File src=NewFile (srcpath);Panax NotoginsengFile dest=NewFile (destpath); - copyFile (SRC, dest); the } + Public Static voidcopyFile (File src,file dest) { ABufferedinputstream bis=NULL; theBufferedoutputstream BOS =NULL; + Try { -bis =NewBufferedinputstream (NewFileInputStream (SRC)); $BOS =NewBufferedoutputstream (NewFileOutputStream (dest)); $ byte[] flush=New byte[1024]; - intlen=0;//the actual length of data obtained - while( -1!= (len=Bis.read (flush))) { theBos.write (flush);//Write Data - }Wuyi Bos.flush (); the}Catch(FileNotFoundException e) { -SYSTEM.OUT.PRINTLN ("File not Found"); Wu e.printstacktrace (); -}Catch(IOException e) { AboutSystem.out.println ("Read stream failed"); $ e.printstacktrace (); -}finally{ - - Try { A if(NULL!=Bos) { + bos.close (); the } - if(NULL!=bis) { $ bis.close (); the } the}Catch(IOException e) { theSystem.out.println ("Shutdown stream failed! "); the e.printstacktrace (); - } in the } the } About}
Copy of Folder