Example usage for java.nio.file StandardCopyOption COPY_ATTRIBUTES

List of usage examples for java.nio.file StandardCopyOption COPY_ATTRIBUTES

Introduction

In this page you can find the example usage for java.nio.file StandardCopyOption COPY_ATTRIBUTES.

Prototype

StandardCopyOption COPY_ATTRIBUTES

To view the source code for java.nio.file StandardCopyOption COPY_ATTRIBUTES.

Click Source Link

Document

Copy attributes to the new file.

Usage

From source file:org.apache.archiva.web.api.DefaultFileUploadService.java

private void copyFile(File sourceFile, File targetPath, String targetFilename, boolean fixChecksums)
        throws IOException {

    Files.copy(sourceFile.toPath(), new File(targetPath, targetFilename).toPath(),
            StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);

    if (fixChecksums) {
        fixChecksums(new File(targetPath, targetFilename));
    }/* w  w w .  ja va2  s  .  com*/
}

From source file:org.csstudio.diirt.util.core.preferences.DIIRTPreferences.java

/**
 * Copy recursively all the files in the {@code from} the given directory
 * {@code to} the given one, {@code excluding} everything inside the
 * provided {@link List}.//from  w  w  w . j  av  a  2 s. c  om
 *
 * @param from      The directory source of the files to be copied.
 * @param to        The directory where files must be copied into.
 * @param excluding The {@link List} of files/folder that must not be copied.
 *                  Inside this list, pathnames must be relative to the
 *                  {@code from} directory.
 * @throws IOException If {@code to} is not a directory or some problems
 *              occurs while copying the files.
 * @throws CompoundIOException If problems occurs copying files.
 */
private static void copyFiles(final File from, final File to, final List<File> excluding)
        throws IOException, CompoundIOException {

    if (from == null || !from.exists() || !from.isDirectory()) {
        return;
    }

    if (to == null) {
        throw new NullPointerException("'to' directory.");
    } else if (!to.exists()) {
        if (!to.mkdirs()) {
            throw new IOException(MessageFormat.format("Unable to create 'to' directory [{0}].", to.getPath()));
        }
    }

    List<Exception> exceptions = new ArrayList<>();

    Arrays.asList(from.listFiles()).stream()
            .filter(f -> !excluding.stream().anyMatch(ff -> f.toString().endsWith(ff.toString())))
            .forEach(f -> {
                if (f.isDirectory()) {

                    File destination = new File(to, f.getName());

                    try {
                        copyFiles(f, destination, excluding);
                    } catch (IOException ioex) {
                        exceptions.add(new IOException(
                                MessageFormat.format("Unable to create to copy files [from: {0}, to: {1}].",
                                        f.toString(), destination.toString())));
                    }
                } else {

                    Path source = f.toPath();
                    Path destination = new File(to, f.getName()).toPath();

                    try {
                        Files.copy(source, destination, StandardCopyOption.COPY_ATTRIBUTES);
                    } catch (IOException ioex) {
                        exceptions.add(new IOException(
                                MessageFormat.format("Unable to create to copy a file [from: {0}, to: {1}].",
                                        source.toString(), destination.toString())));
                    }

                }
            });

    if (!exceptions.isEmpty()) {
        throw new CompoundIOException(MessageFormat.format("Problems copying files [from: {0}, to: {1}].",
                from.toString(), to.toString()), exceptions);
    }

}

From source file:org.tinymediamanager.core.Utils.java

/**
 * copy a file, preserving the attributes
 *
 * @param srcFile/* w w  w.j a va2 s. co  m*/
 *          the file to be copied
 * @param destFile
 *          the target
 * @param overwrite
 *          overwrite the target?
 * @return true/false
 * @throws NullPointerException
 *           if source or destination is {@code null}
 * @throws FileExistsException
 *           if the destination file exists
 * @throws IOException
 *           if source or destination is invalid
 * @throws IOException
 *           if an IO error occurs moving the file
 */
public static boolean copyFileSafe(final Path srcFile, final Path destFile, boolean overwrite)
        throws IOException {
    if (srcFile == null) {
        throw new NullPointerException("Source must not be null");
    }
    if (destFile == null) {
        throw new NullPointerException("Destination must not be null");
    }
    // if (!srcFile.equals(destFile)) {
    if (!srcFile.toAbsolutePath().toString().equals(destFile.toAbsolutePath().toString())) {
        LOGGER.debug("try to copy file " + srcFile + " to " + destFile);
        if (!Files.exists(srcFile)) {
            throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
        }
        if (Files.isDirectory(srcFile)) {
            throw new IOException("Source '" + srcFile + "' is a directory");
        }
        if (!overwrite) {
            if (Files.exists(destFile) && !Files.isSameFile(destFile, srcFile)) {
                // extra check for windows, where the File.equals is case insensitive
                // so we know now, that the File is the same, but the absolute name does not match
                throw new FileExistsException("Destination '" + destFile + "' already exists");
            }
        }
        if (Files.isDirectory(destFile)) {
            throw new IOException("Destination '" + destFile + "' is a directory");
        }

        // rename folder; try 5 times and wait a sec
        boolean rename = false;
        for (int i = 0; i < 5; i++) {
            try {
                // replace existing for changing cASE
                Files.copy(srcFile, destFile, StandardCopyOption.REPLACE_EXISTING,
                        StandardCopyOption.COPY_ATTRIBUTES);
                rename = true;// no exception
            } catch (IOException e) {
            }

            if (rename) {
                break; // ok it worked, step out
            }
            try {
                LOGGER.debug("rename did not work - sleep a while and try again...");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                LOGGER.warn("I'm so excited - could not sleep");
            }
        }

        if (!rename) {
            LOGGER.error("Failed to rename file '" + srcFile + " to " + destFile);
            MessageManager.instance
                    .pushMessage(new Message(MessageLevel.ERROR, srcFile, "message.renamer.failedrename"));
            return false;
        } else {
            LOGGER.info("Successfully moved file from " + srcFile + " to " + destFile);
            return true;
        }
    }
    return true; // files are equal
}

From source file:adalid.util.velocity.BaseBuilder.java

private void copy(String source, String target) throws IOException {
    Path sourcePath = Paths.get(source);
    Path targetPath = Paths.get(target);
    //overwrite existing file, if exists
    CopyOption[] options = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.COPY_ATTRIBUTES };
    Files.copy(sourcePath, targetPath, options);
}

From source file:org.apache.marmotta.platform.core.services.config.ConfigurationServiceImpl.java

protected void saveSecure(final PropertiesConfiguration conf) throws ConfigurationException {
    final File file = conf.getFile();
    try {// w  w  w. j a  va  2 s.  co  m
        if (file == null) {
            throw new ConfigurationException("No file name has been set!");
        } else if ((file.createNewFile() || true) && !file.canWrite()) {
            throw new IOException("Cannot write to file " + file.getAbsolutePath() + ". Is it read-only?");
        }
    } catch (IOException e) {
        throw new ConfigurationException(e.getMessage(), e);
    }
    log.debug("Saving {}", file.getAbsolutePath());

    final String fName = file.getName();
    try {
        int lastDot = fName.lastIndexOf('.');
        lastDot = lastDot > 0 ? lastDot : fName.length();

        final Path configPath = file.toPath();
        // Create a tmp file next to the original
        final Path tmp = Files.createTempFile(configPath.getParent(), fName.substring(0, lastDot) + ".",
                fName.substring(lastDot));
        try {
            Files.copy(configPath, tmp, StandardCopyOption.COPY_ATTRIBUTES,
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException iox) {
            log.error("Could not create temp-file {}: {}", tmp, iox.getMessage());
            throw iox;
        }
        log.trace("using temporary file: {}", tmp);
        // Save the config to the tmp file
        conf.save(tmp.toFile());

        log.trace("tmp saved, now replacing the original file: {}", configPath);
        // Replace the original with the tmp file
        try {
            try {
                Files.move(tmp, configPath, StandardCopyOption.REPLACE_EXISTING,
                        StandardCopyOption.ATOMIC_MOVE);
            } catch (AtomicMoveNotSupportedException amnx) {
                log.trace("atomic move not available: {}, trying without", amnx.getMessage());
                Files.move(tmp, configPath, StandardCopyOption.REPLACE_EXISTING);
            }
        } catch (IOException iox) {
            log.error("Could not write to {}, a backup was created in {}", configPath, tmp);
            throw iox;
        }
        log.info("configuration successfully saved to {}", configPath);
    } catch (final Throwable t) {
        throw new ConfigurationException("Unable to save the configuration to the file " + fName, t);
    }
}