Java nio.2--file or directory copy operation

Source: Internet
Author: User

Copying the entire file tree is a method that can be recursively called per directory and file Files.copy() . There are a few things to consider when using.

    • Before you copy files to a directory, you must first ensure that the directory already exists. The copy source directory, whether empty or not, will generate the target directory. The entire task must be executed in the preVisitDirectory() method.
    • visitFile()the best way to copy each file.
    • When you copy a directory or file, you need to decide whether you want to use REPLACE_EXISTING andCOPY_ATTRIBUTES 选项。
    • If you want to save the properties of the directory you want to copy, you need to postVisitDirectory() do this in the method.
    • If you use the FOLLOW_LINKS option, and there is a looping link in your directory tree pointing to the parent directory, the loop throws an exception in the visitFileFailed() method FileSystemLoopException .
    • If the file does not allow access, you can return it according to your own decision.FileVisitResult.CONTINUE或TERMINATE。
    • If you specify an FOLLOW_LINKS option, you can track the symbolic link file.

The following example uses C:\rafaelnadal a directory copy to C:\rafaelnadal_copy .

Importjava.nio.file.FileSystemLoopException;ImportJava.nio.file.attribute.FileTime;Importjava.io.IOException;Importjava.nio.file.FileVisitOption;ImportJava.nio.file.FileVisitResult;ImportJava.nio.file.FileVisitor;ImportJava.nio.file.Files;ImportJava.nio.file.Path;Importjava.nio.file.Paths;Importjava.nio.file.attribute.BasicFileAttributes;ImportJava.util.EnumSet;Import StaticJava.nio.file.StandardCopyOption.REPLACE_EXISTING;Import StaticJava.nio.file.StandardCopyOption.COPY_ATTRIBUTES;classCopytreeImplementsFilevisitor {Private FinalPath CopyFrom; Private FinalPath CopyTo;  Publiccopytree (Path copyFrom, path CopyTo) { This. CopyFrom =CopyFrom;  This. CopyTo =CopyTo; }    Static voidCopysubtree (Path copyFrom, path CopyTo)throwsIOException {Try{files.copy (CopyFrom, CopyTo, replace_existing, copy_attributes); } Catch(IOException e) {System.err.println ("Unable to copy" + CopyFrom + "[" + E + "]"); }} @Override Publicfilevisitresult postvisitdirectory (Object dir, IOException exc) throwsIOException {if(exc = =NULL) {Path newdir=copyto.resolve (Copyfrom.relativize (Path) dir); Try{FileTime time=files.getlastmodifiedtime (Path) dir);             Files.setlastmodifiedtime (Newdir, time); } Catch(IOException e) {System.err.println ("Unable to copy all attributes to:" + newdir+ "[" +e+ "]"); }         } Else {             Throwexc; }         returnfilevisitresult.continue; } @Override Publicfilevisitresult previsitdirectory (Object dir, basicfileattributes attrs) throwsIOException {System.out.println ("Copy Directory:" +(Path) dir); Path Newdir=copyto.resolve (Copyfrom.relativize (Path) dir); Try{files.copy (Path) dir, Newdir, replace_existing, copy_attributes); } Catch(IOException e) {System.err.println ("Unable to create" + Newdir + "[" + E + "]"); returnFilevisitresult.skip_subtree; }         returnfilevisitresult.continue; } @Override Publicfilevisitresult visitfile (Object file, Basicfileattributes attrs) throwsIOException {System.out.println ("Copy file:" +(Path) file);         Copysubtree (path) file, Copyto.resolve (copyfrom.relativize (path) file)); returnfilevisitresult.continue; } @Override Publicfilevisitresult visitfilefailed (Object file, IOException exc) throwsIOException {if(excinstanceoffilesystemloopexception) {System.err.println ("Cycle was detected:" +(Path) file); } Else{System.err.println ("Error occurred, unable to copy:" + (Path) file+ "[" + exc + "]"); }         returnfilevisitresult.continue; } } classMain { Public Static voidMain (string[] args)throwsIOException {Path copyFrom= Paths.get ("C:/rafaelnadal"); Path CopyTo= Paths.get ("C:/rafaelnadal_copy"); Copytree Walk=NewCopytree (CopyFrom, copyTo); Enumset opts=Enumset.of (filevisitoption.follow_links);     Files.walkfiletree (CopyFrom, opts, Integer.max_value, walk); } } 

Java nio.2--file or directory copy operation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.