1 /**2 * Copy the target directory to the specified directory (can also be used to copy files)3 * @paramsrc Source Path4 * @paramdest Target Path5 * @throwsIOException6 */7 Public Static voidCopydir (file src, file dest)throwsIOException {8 if(!src.exists ()) {//Check if the source path exists9System.out.println ("Source directory does not exist!"));Ten}Else if(Src.isfile ()) {//if the source path is a file One if(Dest.isdirectory ()) { A //cannot copy files to a directory -SYSTEM.OUT.PRINTLN ("Destination path is not a file!")); -}Else { the //Copying Files -FileInputStream FIS =NewFileInputStream (SRC); -FileOutputStream fos =NewFileOutputStream (dest); - byte[] arr =New byte[1024 * 8]; + intLen; - while(len = Fis.read (arr))! =-1) { +Fos.write (arr, 0, Len); A } at fis.close (); - fos.close (); - } -}Else{//if the source path is a directory - if(Dest.isfile ()) { - //cannot copy directory to a file inSYSTEM.OUT.PRINTLN ("Destination path is not a directory!")); -}Else { to //first check if the target exists, does not exist, creates + if(!dest.exists ()) { - dest.mkdirs (); the } * //If the destination path is a directory, recursively call this method for replication $ //get the child files/directories of the source directoryPanax Notoginsengstring[] Subfiles =src.list (); - //traverse the source directory for replication the for(String subfile:subfiles) { +Copydir (NewFile (SRC, subfile),NewFile (dest, Subfile)); A } the } + } - } $ $ /** - * Test Code - * @paramargs the * @throwsIOException - */Wuyi Public Static voidMain (string[] args)throwsIOException { theScanner sc =NewScanner (system.in); -System.out.println ("Please enter source path:"); WuString src =sc.nextline (); -System.out.println ("Please enter the target path:"); AboutString dest =sc.nextline (); $Copydir (NewFile (SRC),NewFile (dest)); -}
A method for replicating directories in Java (recursive)