This is a school Java lesson of an experiment, the title is as follows: programming, according to the specified source and destination location, to complete the specified file or folder (including its subfolders, sub-files) replication.
Here is my implementation, using recursion:
1 Packagecom.simon.myfinal;2 3 ImportJava.io.File;4 ImportJava.io.FileInputStream;5 ImportJava.io.FileOutputStream;6 ImportJava.io.InputStream;7 8 /**9 * Created by Rainmer on 2015/6/28.Ten */ One Public classFileCopy { A Public Static voidMain (string[] args) { -String OldPath = "D:/bower"; -String NewPath = "D:/bowercopy"; theFile dirnew =NewFile (NewPath); -Dirnew.mkdirs ();//You can create a folder in a directory that does not exist - directory (OldPath, NewPath); -System.out.println ("Copy folder succeeded"); + } - + /** A * Copy individual files at * @paramOldPath The file name to copy - * @paramnewpath target file name - */ - Public Static voidCopyFile (String OldPath, String newpath) { - intHasread = 0; -File OldFile =NewFile (oldpath); in if(Oldfile.exists ()) { - Try { toFileInputStream FIS =NewFileInputStream (OldFile);//read in the original file +FileOutputStream fos =NewFileOutputStream (NewPath); - byte[] buffer =New byte[1024]; the while((Hasread = fis.read (buffer))! =-1) {//when the file is not read to the end *Fos.write (buffer, 0, hasread);//Write a file $ }Panax Notoginseng fis.close (); -}Catch(Exception e) { theSYSTEM.OUT.PRINTLN ("Error copying single file operation! "); + e.printstacktrace (); A } the } + } - $ /** $ * - * @paramOldPath the folder path to copy - * @paramNewPath destination Folder path the */ - Public Static voiddirectory (string oldpath, String newpath) {WuyiFile F1 =NewFile (oldpath); thefile[] files = f1.listfiles ();//Listfiles to get all the files and folders under the current folder - for(inti = 0; i < files.length; i++) { Wu if(Files[i].isdirectory ()) { -File dirnew =NewFile (NewPath + file.separator +files[i].getname ()); AboutDirnew.mkdir ();//Create a folder in the destination folder $ //Recursive -Directory (OldPath + file.separator + files[i].getname (), NewPath + File.separator +files[i].getname ()); -}Else { -String FilePath = NewPath + File.separator +files[i].getname (); A CopyFile (Files[i].getabsolutepath (), filePath); + } the - } $ } the}
Replication of the Java Implementation folder (including subfolders, sub-files)-recursion