Java Path Copy nio copy(Path sourcePath, Path targetPath)

Here you can find the source of copy(Path sourcePath, Path targetPath)

Description

copy

License

Open Source License

Declaration

public static void copy(Path sourcePath, Path targetPath) throws IOException 

Method Source Code

//package com.java2s;
/**/*from  w w  w. j av  a  2  s  .c om*/
 * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class Main {
    public static void copy(Path sourcePath, Path targetPath) throws IOException {

        if (!Files.exists(sourcePath)) {
            throw new IOException(sourcePath + " does not exist");
        }

        Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes basicFileAttributes)
                    throws IOException {

                Files.createDirectories(targetPath.resolve(sourcePath.relativize(path)));

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes)
                    throws IOException {

                Path targetFilePath = targetPath.resolve(sourcePath.relativize(path));

                if (!Files.exists(targetFilePath)) {
                    Files.copy(path, targetFilePath);
                }

                return FileVisitResult.CONTINUE;
            }

        });
    }
}

Related

  1. copy(Path source, Path destination)
  2. copy(Path source, Path destination)
  3. copy(Path source, Path target)
  4. copy(Path source, Path target, CopyOption... options)
  5. copy(Path sourcePath, Path destinationPath)
  6. copy(Path src, Path dest, List globPattern)
  7. copy(String filePath, String fileName)
  8. copyAlways(Path source, Path target)
  9. copyAsTrueTempFile(Path source, FileAttribute... attrs)