This topic with the traditional file,inputstream can do, but if the Files,path class to do, although the idea will be difficult, but the code is a lot more concise, the following is the code:
Importjava.io.IOException;ImportJava.nio.file.FileVisitResult;ImportJava.nio.file.Files;ImportJava.nio.file.Path;Importjava.nio.file.Paths;ImportJava.nio.file.SimpleFileVisitor;Importjava.nio.file.attribute.BasicFileAttributes;ImportJava.util.Scanner;//receive two folder paths from the keyboard, copy one of the folders (containing content) to another folder Public classDemo1 { Public Static voidMain (string[] args)throwsIOException {Path path1=getpath ();//Get source folder pathPath Path2=getpath ();//Get destination Folder pathPath Path=path1.getfilename ();//gets the last filename of the source filePath2=path2.resolve (path);//Create a folder to store the contents of the source file in the destination filecopy (path1,path2); } Public Static voidCopy (path path1, path path2)throwsIOException {files.walkfiletree (path1,NewSimplefilevisitor<path>() { //actions to take before accessing the folder@Override PublicFilevisitresult previsitdirectory (Path dir, basicfileattributes attrs)throwsIOException {Path P1=path1.relativize (dir);//Get folder relative pathPath P2=path2.resolve (p1);//create a path in the destination folderFiles.createdirectories (p2);//Create a folder. returnFilevisitresult.continue;//continue to access.} @Override PublicFilevisitresult visitfile (Path file, Basicfileattributes attrs)throwsIOException {Path P1=path1.relativize (file);//gets the relative path of the file relative to the source filePath P2=path2.resolve (p1);//get the path location of the file in the destination fileFiles.copy (file, p2);//copying files using the copy function of the files class returnFilevisitresult.continue;//continue to access.} @Override PublicFilevisitresult visitfilefailed (Path file, IOException exc)throwsIOException {returnFilevisitresult.continue;//access failed, continue access. } }); } Public StaticPath GetPath () {System.out.println ("Please enter a folder!"); String Str=NULL; Scanner SC=NewScanner (system.in); STR=Sc.nextline (); Path Path=paths.get (str);//Get Path if(!files.exists (path)) {System.out.println ("Please enter a folder that exists"); GetPath (); } if(Files.isregularfile (path)) {System.out.println ("Please enter the file!"); GetPath (); } returnpath; }}
Path,files Consolidation, Title: Receive two folder paths from the keyboard, copy one of the folders (containing content) to another folder