Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/sample/nio/file/Copy.java
38829 views
/*1* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.2*3* Redistribution and use in source and binary forms, with or without4* modification, are permitted provided that the following conditions5* are met:6*7* - Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9*10* - Redistributions in binary form must reproduce the above copyright11* notice, this list of conditions and the following disclaimer in the12* documentation and/or other materials provided with the distribution.13*14* - Neither the name of Oracle nor the names of its15* contributors may be used to endorse or promote products derived16* from this software without specific prior written permission.17*18* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS19* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,20* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR21* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR22* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,23* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,24* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.29*/3031/*32* This source code is provided to illustrate the usage of a given feature33* or technique and has been deliberately simplified. Additional steps34* required for a production-quality application, such as security checks,35* input validation and proper error handling, might not be present in36* this sample code.37*/383940import java.nio.file.*;41import static java.nio.file.StandardCopyOption.*;42import java.nio.file.attribute.*;43import static java.nio.file.FileVisitResult.*;44import java.io.IOException;45import java.util.*;4647/**48* Sample code that copies files in a similar manner to the cp(1) program.49*/5051public class Copy {5253/**54* Returns {@code true} if okay to overwrite a file ("cp -i")55*/56static boolean okayToOverwrite(Path file) {57String answer = System.console().readLine("overwrite %s (yes/no)? ", file);58return (answer.equalsIgnoreCase("y") || answer.equalsIgnoreCase("yes"));59}6061/**62* Copy source file to target location. If {@code prompt} is true then63* prompt user to overwrite target if it exists. The {@code preserve}64* parameter determines if file attributes should be copied/preserved.65*/66static void copyFile(Path source, Path target, boolean prompt, boolean preserve) {67CopyOption[] options = (preserve) ?68new CopyOption[] { COPY_ATTRIBUTES, REPLACE_EXISTING } :69new CopyOption[] { REPLACE_EXISTING };70if (!prompt || Files.notExists(target) || okayToOverwrite(target)) {71try {72Files.copy(source, target, options);73} catch (IOException x) {74System.err.format("Unable to copy: %s: %s%n", source, x);75}76}77}7879/**80* A {@code FileVisitor} that copies a file-tree ("cp -r")81*/82static class TreeCopier implements FileVisitor<Path> {83private final Path source;84private final Path target;85private final boolean prompt;86private final boolean preserve;8788TreeCopier(Path source, Path target, boolean prompt, boolean preserve) {89this.source = source;90this.target = target;91this.prompt = prompt;92this.preserve = preserve;93}9495@Override96public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {97// before visiting entries in a directory we copy the directory98// (okay if directory already exists).99CopyOption[] options = (preserve) ?100new CopyOption[] { COPY_ATTRIBUTES } : new CopyOption[0];101102Path newdir = target.resolve(source.relativize(dir));103try {104Files.copy(dir, newdir, options);105} catch (FileAlreadyExistsException x) {106// ignore107} catch (IOException x) {108System.err.format("Unable to create: %s: %s%n", newdir, x);109return SKIP_SUBTREE;110}111return CONTINUE;112}113114@Override115public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {116copyFile(file, target.resolve(source.relativize(file)),117prompt, preserve);118return CONTINUE;119}120121@Override122public FileVisitResult postVisitDirectory(Path dir, IOException exc) {123// fix up modification time of directory when done124if (exc == null && preserve) {125Path newdir = target.resolve(source.relativize(dir));126try {127FileTime time = Files.getLastModifiedTime(dir);128Files.setLastModifiedTime(newdir, time);129} catch (IOException x) {130System.err.format("Unable to copy all attributes to: %s: %s%n", newdir, x);131}132}133return CONTINUE;134}135136@Override137public FileVisitResult visitFileFailed(Path file, IOException exc) {138if (exc instanceof FileSystemLoopException) {139System.err.println("cycle detected: " + file);140} else {141System.err.format("Unable to copy: %s: %s%n", file, exc);142}143return CONTINUE;144}145}146147static void usage() {148System.err.println("java Copy [-ip] source... target");149System.err.println("java Copy -r [-ip] source-dir... target");150System.exit(-1);151}152153public static void main(String[] args) throws IOException {154boolean recursive = false;155boolean prompt = false;156boolean preserve = false;157158// process options159int argi = 0;160while (argi < args.length) {161String arg = args[argi];162if (!arg.startsWith("-"))163break;164if (arg.length() < 2)165usage();166for (int i=1; i<arg.length(); i++) {167char c = arg.charAt(i);168switch (c) {169case 'r' : recursive = true; break;170case 'i' : prompt = true; break;171case 'p' : preserve = true; break;172default : usage();173}174}175argi++;176}177178// remaining arguments are the source files(s) and the target location179int remaining = args.length - argi;180if (remaining < 2)181usage();182Path[] source = new Path[remaining-1];183int i=0;184while (remaining > 1) {185source[i++] = Paths.get(args[argi++]);186remaining--;187}188Path target = Paths.get(args[argi]);189190// check if target is a directory191boolean isDir = Files.isDirectory(target);192193// copy each source file/directory to target194for (i=0; i<source.length; i++) {195Path dest = (isDir) ? target.resolve(source[i].getFileName()) : target;196197if (recursive) {198// follow links when copying files199EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);200TreeCopier tc = new TreeCopier(source[i], dest, prompt, preserve);201Files.walkFileTree(source[i], opts, Integer.MAX_VALUE, tc);202} else {203// not recursive so source must not be a directory204if (Files.isDirectory(source[i])) {205System.err.format("%s: is a directory%n", source[i]);206continue;207}208copyFile(source[i], dest, prompt, preserve);209}210}211}212}213214215