Example usage for java.nio.file StandardCopyOption REPLACE_EXISTING

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

Introduction

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

Prototype

StandardCopyOption REPLACE_EXISTING

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

Click Source Link

Document

Replace an existing file if it exists.

Usage

From source file:fr.inria.soctrace.tools.ocelotl.core.caches.DichotomyCache.java

/**
 * Save the cache of the current trace to the specified path
 * /*  w w  w .ja  v a  2s  .  c om*/
 * @param oParam
 *            current parameters
 * @param destPath
 *            path to save the file
 */
public void saveDichotomyCacheTo(OcelotlParameters oParam, String destPath) {
    // Get the current cache file
    CacheParameters params = new CacheParameters(oParam);
    File source = null;

    // Look for the corresponding file
    for (CacheParameters par : cachedDichotomy.keySet()) {
        if (similarParameters(params, par)) {
            source = cachedDichotomy.get(par);
        }
    }

    if (source != null) {
        File dest = new File(destPath);

        try {
            Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        logger.error("[DICHOTOMY CACHE] No corresponding cache file was found");
    }
}

From source file:de.tiqsolutions.hdfs.HadoopFileSystemProvider.java

@Override
public void copy(Path source, Path target, CopyOption... options) throws IOException {
    List<CopyOption> optionList = Arrays.asList(options);
    if (!optionList.contains(StandardCopyOption.REPLACE_EXISTING)) {
        if (Files.exists(target))
            throw new java.nio.file.FileAlreadyExistsException(source.toString(), target.toString(),
                    "could not copy file to destination");
    } else {//from w w  w  .  j a  va 2  s  . co  m
        Files.deleteIfExists(target);
    }

    FileSystem sourceFS = source.getFileSystem();
    FileSystem targetFS = target.getFileSystem();

    if (optionList.contains(HadoopCopyOption.REMOTE_COPY) && sourceFS.equals(targetFS)) {

        remoteCopy(source, target, options);
        return;

    }
    try (SeekableByteChannel sourceChannel = sourceFS.provider().newByteChannel(source,
            EnumSet.of(StandardOpenOption.READ))) {

        Set<StandardOpenOption> openOptions = EnumSet.of(StandardOpenOption.WRITE);

        if (optionList.contains(StandardCopyOption.REPLACE_EXISTING))
            openOptions.add(StandardOpenOption.CREATE);
        else
            openOptions.add(StandardOpenOption.CREATE_NEW);
        List<FileAttribute<?>> fileAttributes = new ArrayList<>();
        if (optionList.contains(StandardCopyOption.COPY_ATTRIBUTES)) {

            Set<String> sourceAttrViews = sourceFS.supportedFileAttributeViews();
            Set<String> targetAttrViews = targetFS.supportedFileAttributeViews();
            if (sourceAttrViews.contains(PosixFileAttributeViewImpl.NAME)
                    && targetAttrViews.contains(PosixFileAttributeViewImpl.NAME)) {
                PosixFileAttributes posixAttributes = sourceFS.provider().readAttributes(source,
                        PosixFileAttributes.class);
                fileAttributes.add(PosixFilePermissions.asFileAttribute(posixAttributes.permissions()));
            }

            if (sourceAttrViews.contains(HadoopFileAttributeViewImpl.NAME)
                    && targetAttrViews.contains(HadoopFileAttributeViewImpl.NAME)) {
                final HadoopFileAttributes hdfsAttributes = sourceFS.provider().readAttributes(source,
                        HadoopFileAttributes.class);
                fileAttributes.add(new FileAttribute<Long>() {
                    @Override
                    public String name() {
                        return HadoopFileAttributeViewImpl.NAME + ":blockSize";
                    }

                    @Override
                    public Long value() {
                        return hdfsAttributes.getBlockSize();
                    }
                });
                fileAttributes.add(new FileAttribute<Short>() {
                    @Override
                    public String name() {
                        return HadoopFileAttributeViewImpl.NAME + ":replication";
                    }

                    @Override
                    public Short value() {
                        return hdfsAttributes.getReplication();
                    }
                });

            }
        }

        FileAttribute<?>[] attributes = fileAttributes.toArray(new FileAttribute<?>[fileAttributes.size()]);

        try (SeekableByteChannel targetChannel = targetFS.provider().newByteChannel(target, openOptions,
                attributes)) {
            int buffSize = getConfiguration().getInt(DFSConfigKeys.DFS_STREAM_BUFFER_SIZE_KEY,
                    DFSConfigKeys.DFS_STREAM_BUFFER_SIZE_DEFAULT);
            ByteBuffer buffer = ByteBuffer.allocate(buffSize);
            buffer.clear();
            while (sourceChannel.read(buffer) > 0) {
                buffer.flip();
                targetChannel.write(buffer);
                buffer.clear();
            }

        }
        if (optionList.contains(StandardCopyOption.COPY_ATTRIBUTES)) {
            BasicFileAttributes attrs = sourceFS.provider().readAttributes(source, BasicFileAttributes.class);
            BasicFileAttributeView view = targetFS.provider().getFileAttributeView(target,
                    BasicFileAttributeView.class);
            view.setTimes(attrs.lastModifiedTime(), attrs.lastAccessTime(), attrs.creationTime());

        }

    }

}

From source file:org.apache.nifi.registry.client.impl.JerseyExtensionBundleVersionClient.java

@Override
public File writeBundleVersionContent(final String bundleId, final String version, final File directory)
        throws IOException, NiFiRegistryException {

    if (StringUtils.isBlank(bundleId)) {
        throw new IllegalArgumentException("Bundle id cannot be null or blank");
    }/*  w w  w .  j  a  va  2s.c om*/

    if (StringUtils.isBlank(version)) {
        throw new IllegalArgumentException("Version cannot be null or blank");
    }

    if (directory == null || !directory.exists() || !directory.isDirectory()) {
        throw new IllegalArgumentException("Directory must exist and be a valid directory");
    }

    return executeAction("Error getting extension bundle version", () -> {
        final WebTarget target = extensionBundlesTarget.path("{bundleId}/versions/{version}/content")
                .resolveTemplate("bundleId", bundleId).resolveTemplate("version", version);

        final Response response = getRequestBuilder(target).accept(MediaType.APPLICATION_OCTET_STREAM_TYPE)
                .get();

        final String contentDispositionHeader = response.getHeaderString("Content-Disposition");
        if (StringUtils.isBlank(contentDispositionHeader)) {
            throw new IllegalStateException("Content-Disposition header was blank or missing");
        }

        final int equalsIndex = contentDispositionHeader.lastIndexOf("=");
        final String filename = contentDispositionHeader.substring(equalsIndex + 1).trim();
        final File bundleFile = new File(directory, filename);

        try (final InputStream responseInputStream = response.readEntity(InputStream.class)) {
            Files.copy(responseInputStream, bundleFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            return bundleFile;
        } catch (Exception e) {
            throw new IllegalStateException("Unable to write bundle content due to: " + e.getMessage(), e);
        }
    });
}

From source file:com.cloudbees.clickstack.util.Files2.java

/**
 * Copy every file of given {@code zipFile} beginning with given {@code zipSubPath} to {@code destDir}
 *
 * @param zipFile//from   w  ww  . j ava2 s .c om
 * @param zipSubPath must start with a "/"
 * @param destDir
 * @throws RuntimeIOException
 */
public static void unzipSubDirectoryIfExists(@Nonnull Path zipFile, @Nonnull String zipSubPath,
        @Nonnull final Path destDir) throws RuntimeIOException {
    Preconditions.checkArgument(zipSubPath.startsWith("/"), "zipSubPath '%s' must start with a '/'",
            zipSubPath);
    try {
        //if the destination doesn't exist, create it
        if (Files.notExists(destDir)) {
            logger.trace("Create dir: {}", destDir);
            Files.createDirectories(destDir);
        }

        try (FileSystem zipFileSystem = createZipFileSystem(zipFile, false)) {
            final Path root = zipFileSystem.getPath(zipSubPath);
            if (Files.notExists(root)) {
                logger.trace("Zip sub path {} does not exist in {}", zipSubPath, zipFile);
                return;
            }

            //walk the zip file tree and copy files to the destination
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    try {
                        final Path destFile = Paths.get(destDir.toString(), root.relativize(file).toString());
                        logger.trace("Extract file {} to {} as {}", file, destDir, destFile);
                        Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING,
                                StandardCopyOption.COPY_ATTRIBUTES);
                    } catch (IOException | RuntimeException e) {
                        logger.warn("Exception copying file '" + file + "' with root '" + root
                                + "' to destDir '" + destDir + "', ignore file", e);
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    dir.relativize(root).toString();
                    final Path dirToCreate = Paths.get(destDir.toString(), root.relativize(dir).toString());

                    if (Files.notExists(dirToCreate)) {
                        logger.trace("Create dir {}", dirToCreate);
                        Files.createDirectory(dirToCreate);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    } catch (IOException e) {
        throw new RuntimeIOException("Exception expanding " + zipFile + ":" + zipSubPath + " to " + destDir, e);
    }
}

From source file:com.kantenkugel.discordbot.jdocparser.JDoc.java

private static void download() {
    try {/*from w ww .  j av  a2s.c  o  m*/
        JenkinsBuild lastBuild = JenkinsApi.JDA_JENKINS.getLastSuccessfulBuild();
        if (lastBuild != null) {
            JDocUtil.LOG.debug("Downloading JDA docs...");
            ResponseBody body = null;
            try {
                String artifactUrl = lastBuild.artifacts.get("JDA-javadoc").getLink();
                Response res = Bot.httpClient.newCall(new Request.Builder().url(artifactUrl).get().build())
                        .execute();
                if (!res.isSuccessful()) {
                    JDocUtil.LOG.warn("OkHttp returned failure for " + artifactUrl);
                    return;
                }
                body = res.body();
                final InputStream is = body.byteStream();
                Files.copy(is, JDocUtil.LOCAL_DOC_PATH, StandardCopyOption.REPLACE_EXISTING);
                is.close();
                JDocUtil.LOG.debug("Done downloading JDA docs");
            } catch (Exception e) {
                JDocUtil.LOG.error("Error downloading jdoc jar", e);
            } finally {
                if (body != null)
                    body.close();
            }
        } else {
            JDocUtil.LOG.warn("There was no Jenkins build?! Skipping download");
        }
    } catch (IOException ex) {
        JDocUtil.LOG.warn("Could not contact Jenkins, skipping download");
    }
}

From source file:org.elasticsearch.test.rest.yaml.ESClientYamlSuiteTestCase.java

/**
 * Returns a new FileSystem to read REST resources, or null if they
 * are available from classpath.//  w  ww.j  av  a2s.  co  m
 */
@SuppressForbidden(reason = "proper use of URL, hack around a JDK bug")
protected static FileSystem getFileSystem() throws IOException {
    // REST suite handling is currently complicated, with lots of filtering and so on
    // For now, to work embedded in a jar, return a ZipFileSystem over the jar contents.
    URL codeLocation = FileUtils.class.getProtectionDomain().getCodeSource().getLocation();
    boolean loadPackaged = RandomizedTest.systemPropertyAsBoolean(REST_LOAD_PACKAGED_TESTS, true);
    if (codeLocation.getFile().endsWith(".jar") && loadPackaged) {
        try {
            // hack around a bug in the zipfilesystem implementation before java 9,
            // its checkWritable was incorrect and it won't work without write permissions.
            // if we add the permission, it will open jars r/w, which is too scary! so copy to a safe r-w location.
            Path tmp = Files.createTempFile(null, ".jar");
            try (InputStream in = FileSystemUtils.openFileURLStream(codeLocation)) {
                Files.copy(in, tmp, StandardCopyOption.REPLACE_EXISTING);
            }
            return FileSystems.newFileSystem(new URI("jar:" + tmp.toUri()), Collections.emptyMap());
        } catch (URISyntaxException e) {
            throw new IOException("couldn't open zipfilesystem: ", e);
        }
    } else {
        return null;
    }
}

From source file:org.eclipse.winery.repository.backend.filebased.FilebasedRepository.java

/**
 * {@inheritDoc}/*www. j  a va 2s. c  o  m*/
 */
@Override
public void putContentToFile(RepositoryFileReference ref, InputStream inputStream, MediaType mediaType)
        throws IOException {
    if (mediaType == null) {
        // quick hack for storing mime type called this method
        assert (ref.getFileName().endsWith(Constants.SUFFIX_MIMETYPE));
        // we do not need to store the mime type of the file containing the mime type
        // information
    } else {
        this.setMimeType(ref, mediaType);
    }
    Path targetPath = this.ref2AbsolutePath(ref);
    // ensure that parent directory exists
    FileUtils.createDirectory(targetPath.getParent());

    try {
        Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);
    } catch (IllegalStateException e) {
        FilebasedRepository.logger.debug("Guessing that stream with length 0 is to be written to a file", e);
        // copy throws an "java.lang.IllegalStateException: Stream already closed" if the
        // InputStream contains 0 bytes
        // For instance, this case happens if SugarCE-6.4.2.zip.removed is tried to be uploaded
        // We work around the Java7 issue and create an empty file
        if (Files.exists(targetPath)) {
            // semantics of putContentToFile: existing content is replaced without notification
            Files.delete(targetPath);
        }
        Files.createFile(targetPath);
    }
}

From source file:hydrograph.ui.dataviewer.filemanager.DataViewerFileManager.java

private void copyCSVDebugFileToDataViewerStagingArea(JobDetails jobDetails, String csvDebugFileAbsolutePath,
        String dataViewerDebugFile, boolean isOverWritten) throws IOException, JSchException {
    if (!jobDetails.isRemote()) {
        String sourceFile = csvDebugFileAbsolutePath.trim();
        File file = new File(dataViewerDebugFile);
        if (!file.exists() || isOverWritten) {
            Files.copy(Paths.get(sourceFile), Paths.get(dataViewerDebugFile),
                    StandardCopyOption.REPLACE_EXISTING);
        }//from   w  w  w.  ja  v  a 2 s . c  o  m
    } else {
        File file = new File(dataViewerDebugFile);
        if (!file.exists() || isOverWritten) {
            SCPUtility.INSTANCE.scpFileFromRemoteServer(jobDetails.getHost(), jobDetails.getUsername(),
                    jobDetails.getPassword(), csvDebugFileAbsolutePath.trim(), getDataViewerDebugFilePath());
        }
    }
}

From source file:com.codesourcery.internal.installer.ui.pages.ResultsPage.java

/**
 * Copy the log file to a location outside of the default configuration 
 * area so that it's accessible after the installer has exited and self-deleted.
 *///from ww w  .j  a  va  2s  .c  o  m
private void copyLog() {

    if (logFile != null) {
        // Already copied log.
        return;
    }

    IPath logDirPath = Installer.getDefault().getLogPath();
    try {
        // Copy the platform log file
        if (Installer.getDefault().isCopyLog()) {
            File originalLogFile = Platform.getLogFileLocation().toFile();
            logFile = logDirPath.append(originalLogFile.getName()).toFile();
            Files.copy(originalLogFile.toPath(), logFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }
        // Use the platform log file
        else {
            logFile = Platform.getLogFileLocation().toFile();
        }
    } catch (IOException e) {
        Installer.log(e);
    }
}

From source file:codes.thischwa.c5c.impl.LocalConnector.java

@Override
public void upload(String urlDirectory, String sanitizedName, InputStream in) throws C5CException {
    Path parentFolder = buildRealPathAndCheck(urlDirectory);
    Path fileToSave = parentFolder.resolve(sanitizedName);
    try {//  www.ja  v a  2 s . c  o  m
        Files.deleteIfExists(fileToSave);
        Files.copy(in, fileToSave, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new FilemanagerException(FilemanagerAction.UPLOAD, FilemanagerException.Key.InvalidFileUpload,
                sanitizedName);
    }
}