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:au.org.ands.vocabs.toolkit.provider.harvest.FileHarvestProvider.java

/** Do a harvest. Update the message parameter with the result
 * of the harvest./*from   w ww.  jav a  2s  .c  o m*/
 * NB: if delete is true, Tomcat must have write access, in order
 * to be able to delete the file successfully. However, a failed
 * deletion will not per se cause the subtask to fail.
 * @param version The version to which access points are to be added.
 * @param format The format of the file(s) to be harvested.
 * @param filePath The path to the file or directory to be harvested.
 * @param outputPath The directory in which to store output files.
 * @param delete True, if successfully harvested files are to be deleted.
 * @param results HashMap representing the result of the harvest.
 * @return True, iff the harvest succeeded.
 */
public final boolean getHarvestFiles(final Version version, final String format, final String filePath,
        final String outputPath, final boolean delete, final HashMap<String, String> results) {
    ToolkitFileUtils.requireDirectory(outputPath);
    Path filePathPath = Paths.get(filePath);
    Path outputPathPath = Paths.get(outputPath);
    if (Files.isDirectory(filePathPath)) {
        logger.debug("Harvesting file(s) from directory " + filePath);
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(filePathPath)) {
            for (Path entry : stream) {
                // Only harvest files. E.g., no recursive
                // directory searching.
                if (Files.isRegularFile(entry)) {
                    logger.debug("Harvesting file:" + entry.toString());
                    Path target = outputPathPath.resolve(entry.getFileName());
                    Files.copy(entry, target, StandardCopyOption.REPLACE_EXISTING);
                    AccessPointUtils.createFileAccessPoint(version, format, target);
                    if (delete) {
                        logger.debug("Deleting file: " + entry.toString());
                        try {
                            Files.delete(entry);
                        } catch (AccessDeniedException e) {
                            logger.error("Unable to delete file: " + entry.toString(), e);
                        }
                    }
                }
            }
        } catch (DirectoryIteratorException | IOException ex) {
            results.put(TaskStatus.EXCEPTION, "Exception in getHarvestFiles while copying file");
            logger.error("Exception in getHarvestFiles while copying file:", ex);
            return false;
        }
    } else {
        logger.debug("Harvesting file: " + filePath);
        try {
            Path target = outputPathPath.resolve(filePathPath.getFileName());
            Files.copy(filePathPath, target, StandardCopyOption.REPLACE_EXISTING);
            AccessPointUtils.createFileAccessPoint(version, format, target);
            if (delete) {
                logger.debug("Deleting file: " + filePathPath.toString());
                try {
                    Files.delete(filePathPath);
                } catch (AccessDeniedException e) {
                    logger.error("Unable to delete file: " + filePathPath.toString(), e);
                }
            }
        } catch (IOException e) {
            results.put(TaskStatus.EXCEPTION, "Exception in getHarvestFiles while copying file");
            logger.error("Exception in getHarvestFiles while copying file:", e);
            return false;
        }
    }
    // If we reached here, success, so return true.
    return true;
}

From source file:de._692b8c32.cdlauncher.tasks.GithubReleasesDownloadTask.java

@Override
public void doWork() {
    setProgress(-1);/*from www  . j  av a  2s. c  om*/

    try {
        String realUrl = null;
        HttpClient client = HttpClients.createDefault();
        if (version.getValue() == null) {
            Pattern pattern = Pattern
                    .compile("<ul class=\"release-downloads\"> <li> <a href=\"([^\"]*)\" rel=\"nofollow\">");
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                    client.execute(new HttpGet(baseUrl + "latest")).getEntity().getContent()))) {
                Matcher matcher = pattern
                        .matcher(reader.lines().collect(Collectors.joining(" ")).replace("  ", ""));
                if (matcher.find()) {
                    realUrl = baseUrl.substring(0,
                            baseUrl.indexOf('/', baseUrl.indexOf('/', baseUrl.indexOf('/') + 1) + 1))
                            + matcher.group(1);
                }
            }
        } else {
            realUrl = baseUrl + "download/" + version.getValue() + "/OpenRA-" + version.getValue() + ".zip";
        }

        if (realUrl == null) {
            throw new RuntimeException("Failed to find real url");
        } else {
            try (InputStream stream = client.execute(new HttpGet(realUrl)).getEntity().getContent()) {
                Files.copy(stream, cacheFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }
        }
    } catch (IOException ex) {
        throw new RuntimeException("Could not download data", ex);
    }
}

From source file:org.apache.tika.parser.jdbc.SQLite3DBParser.java

@Override
protected String getConnectionString(InputStream is, Metadata metadata, ParseContext context)
        throws IOException {
    TikaInputStream tis = TikaInputStream.cast(is);
    //if this is a TikaInputStream, use that to spool is to disk or
    //use original underlying file.
    if (tis != null) {
        Path dbFile = tis.getPath();
        return "jdbc:sqlite:" + dbFile.toAbsolutePath().toString();
    } else {/*from   w  ww .  j a va  2  s  . co m*/
        //if not TikaInputStream, create own tmpResources.
        tmpFile = Files.createTempFile("tika-sqlite-tmp", "");
        Files.copy(is, tmpFile, StandardCopyOption.REPLACE_EXISTING);
        return "jdbc:sqlite:" + tmpFile.toAbsolutePath().toString();
    }
}

From source file:com.reactive.hzdfs.dll.JarFileSharingService.java

@Override
protected FileChunkHandler newWriteHandler(String dirPath) throws IOException {
    return new BufferedStreamChunkHandler(dirPath) {
        /**/*  w w w  .ja v  a 2s  . com*/
         * Override the default behaviour to keep a backup
         * @throws IOException 
         */
        @Override
        protected void moveExistingFile() throws IOException {
            //super.moveExistingFile();

            try {
                if (file.exists()) {
                    Path fp = file.toPath();
                    Path backupFile = Files.move(fp,
                            fp.resolveSibling(file.getName() + ".bkp."
                                    + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())),
                            StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);

                    log.info("Backup file created- " + backupFile);
                }

                file.createNewFile();
            } catch (IOException e) {
                log.warn("Backup not taken. Going with default replace and copy. error => " + e.getMessage());
                log.debug("", e);
                super.moveExistingFile();
            }

        }
    };
}

From source file:org.cloudfoundry.dependency.in.InAction.java

private Mono<Void> writeArchive(InputStream content) {
    try (InputStream in = content) {
        Files.createDirectories(this.destination);
        Files.copy(in, getArchiveFile(), StandardCopyOption.REPLACE_EXISTING);
        return Mono.empty();
    } catch (IOException e) {
        throw Exceptions.propagate(e);
    }/*ww w .ja  v a  2 s.  c  o  m*/
}

From source file:com.collaborne.jsonschema.generator.pojo.PojoGeneratorSmokeTest.java

@After
public void tearDown() throws IOException {
    // Dump the contents of the file system
    Path dumpStart = fs.getPath("/");
    Files.walkFileTree(dumpStart, new SimpleFileVisitor<Path>() {
        @Override// www  .j a  va2s .  c  o m
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            System.out.println("> " + file);
            System.out.println(new String(Files.readAllBytes(file), StandardCharsets.UTF_8));

            // Copy the file if wanted
            if (DUMP_DIRECTORY != null) {
                Path dumpTarget = Paths.get(DUMP_DIRECTORY, name.getMethodName());
                Path target = dumpTarget.resolve(dumpStart.relativize(file).toString());
                Files.createDirectories(target.getParent());
                Files.copy(file, target, StandardCopyOption.REPLACE_EXISTING);
            }
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:com.googlecode.download.maven.plugin.internal.cache.DownloadCache.java

public void install(URI uri, File outputFile, String md5, String sha1, String sha512) throws Exception {
    if (md5 == null) {
        md5 = SignatureUtils.computeSignatureAsString(outputFile, MessageDigest.getInstance("MD5"));
    }/*from  w ww  .  j  a va  2s .  c  o  m*/
    if (sha1 == null) {
        sha1 = SignatureUtils.computeSignatureAsString(outputFile, MessageDigest.getInstance("SHA1"));
    }
    if (sha512 == null) {
        sha512 = SignatureUtils.computeSignatureAsString(outputFile, MessageDigest.getInstance("SHA-512"));
    }
    String entry = getEntry(uri, md5, sha1, sha512);
    if (entry != null) {
        return; // entry already here
    }
    String fileName = outputFile.getName() + '_' + DigestUtils.md5Hex(uri.toString());
    Files.copy(outputFile.toPath(), new File(this.basedir, fileName).toPath(),
            StandardCopyOption.REPLACE_EXISTING);
    // update index
    this.index.put(uri, fileName);
}

From source file:org.apdplat.superword.extract.HyphenExtractor.java

public static Map<String, AtomicInteger> parseZip(String zipFile) {
    Map<String, AtomicInteger> data = new HashMap<>();
    LOGGER.info("?ZIP" + zipFile);
    try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), WordClassifier.class.getClassLoader())) {
        for (Path path : fs.getRootDirectories()) {
            LOGGER.info("?" + path);
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

                @Override/*from   w  w  w  .  jav a2  s.c o m*/
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    LOGGER.info("?" + file);
                    // ?
                    Path temp = Paths.get("target/origin-html-temp.txt");
                    Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING);
                    Map<String, AtomicInteger> rs = parseFile(temp.toFile().getAbsolutePath());
                    rs.keySet().forEach(k -> {
                        data.putIfAbsent(k, new AtomicInteger());
                        data.get(k).addAndGet(rs.get(k).get());
                    });
                    return FileVisitResult.CONTINUE;
                }

            });
        }
    } catch (Exception e) {
        LOGGER.error("?", e);
    }
    return data;
}

From source file:com.liferay.sync.engine.util.SyncClientUpdater.java

public static void update(SyncVersion syncVersion) throws Exception {
    if (syncVersion == null) {
        syncVersion = getLatestSyncVersion();
    }/*w  w w  .  ja v a2  s .  c o  m*/

    if (syncVersion == null) {
        return;
    }

    HttpResponse httpResponse = execute(syncVersion.getUrl());

    if (httpResponse == null) {
        return;
    }

    HttpEntity httpEntity = httpResponse.getEntity();
    Path filePath = getFilePath(httpResponse);

    Files.copy(httpEntity.getContent(), filePath, StandardCopyOption.REPLACE_EXISTING);

    Desktop desktop = Desktop.getDesktop();

    desktop.open(filePath.toFile());
}

From source file:org.craftercms.studio.impl.v1.asset.processing.AbstractAssetProcessor.java

private Path moveToTmpFile(String repoPath, Path filePath) throws IOException {
    Path tmpFilePath = createTmpFile(repoPath);

    return Files.move(filePath, tmpFilePath, StandardCopyOption.ATOMIC_MOVE,
            StandardCopyOption.REPLACE_EXISTING);
}