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:com.skynetcomputing.skynetclient.persistence.PersistenceManager.java

/**
 * Reads task file and initiates new task. Wipes current task directory.
 * TaskInfo is saved to file, and from now on can be retrieved with
 * getCurrentTask()//  w  w  w .ja  v a2s  .  c  o m
 *
 * @param inputFile
 * @return
 * @throws IOException
 * @throws ClassNotFoundException
 * @throws ParseException
 */
public SrzTask saveTaskFile(File inputFile) throws IOException, ClassNotFoundException, ParseException {
    clearTask();
    SrzTask task = readTaskFile(inputFile);
    File outputFile = new File(rootDir + TASK_DIR + task.getID() + SrzTask.EXT);
    Files.copy(inputFile.toPath(), outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    return task;
}

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

private Mono<Void> writeVersion() {
    try (InputStream in = new ByteArrayInputStream(new VersionHolder(this.request.getVersion().getRef())
            .toRepositoryVersion().getBytes(Charset.defaultCharset()))) {
        Files.createDirectories(this.destination);
        Files.copy(in, getVersionFile(), StandardCopyOption.REPLACE_EXISTING);
        return Mono.empty();
    } catch (IOException e) {
        throw Exceptions.propagate(e);
    }// w w w.  j  a v  a 2 s .c  o  m
}

From source file:org.eclipse.cdt.arduino.core.internal.board.ArduinoBoardManager.java

public ArduinoBoardManager() {
    new Job(Messages.ArduinoBoardManager_0) {
        protected IStatus run(IProgressMonitor monitor) {
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpGet get = new HttpGet("http://downloads.arduino.cc/packages/package_index.json"); //$NON-NLS-1$
                try (CloseableHttpResponse response = client.execute(get)) {
                    if (response.getStatusLine().getStatusCode() >= 400) {
                        return new Status(IStatus.ERROR, Activator.getId(),
                                response.getStatusLine().getReasonPhrase());
                    } else {
                        HttpEntity entity = response.getEntity();
                        if (entity == null) {
                            return new Status(IStatus.ERROR, Activator.getId(), Messages.ArduinoBoardManager_1);
                        }/*from   w  w w. ja va 2  s . c  o m*/
                        Files.createDirectories(packageIndexPath.getParent());
                        Files.copy(entity.getContent(), packageIndexPath, StandardCopyOption.REPLACE_EXISTING);
                    }
                }
            } catch (IOException e) {
                return new Status(IStatus.ERROR, Activator.getId(), e.getLocalizedMessage(), e);
            }
            return Status.OK_STATUS;
        }
    }.schedule();
}

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

public void install(String url, File outputFile, String md5, String sha1, String sha512) throws Exception {
    if (md5 == null) {
        md5 = SignatureUtils.computeSignatureAsString(outputFile, MessageDigest.getInstance("MD5"));
    }/*from  w  w w . j  a v  a2s  .c om*/
    if (sha1 == null) {
        sha1 = SignatureUtils.computeSignatureAsString(outputFile, MessageDigest.getInstance("SHA1"));
    }
    if (sha512 == null) {
        sha512 = SignatureUtils.computeSignatureAsString(outputFile, MessageDigest.getInstance("SHA-512"));
    }
    CachedFileEntry entry = getEntry(url, md5, sha1, sha512);
    if (entry != null) {
        return; // entry already here
    }
    entry = new CachedFileEntry();
    entry.fileName = outputFile.getName() + '_' + DigestUtils.md5Hex(url);
    Files.copy(outputFile.toPath(), new File(this.basedir, entry.fileName).toPath(),
            StandardCopyOption.REPLACE_EXISTING);
    // update index
    loadIndex();
    this.index.put(url, entry);
    saveIndex();
}

From source file:view.BackgroundImageController.java

public void saveBackgroundImage(String savePath) {
    if (resourceImagePath == null) {
        return;//www . j a  va2  s. c  om
    }

    Path destPath = Paths.get(savePath + ".background");
    try {
        if (!resourceImagePath.startsWith("maps")) {
            Path sourcePath = Paths.get(resourceImagePath);
            Files.copy(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING);
        } else {
            InputStream backgroundFileStream = ClassLoader.getSystemResourceAsStream(resourceImagePath);
            Files.copy(backgroundFileStream, destPath, StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (IOException ex) {
        Logger.getLogger(BackgroundImageController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.wildfly.plugin.server.Archives.java

private static Path getArchive(final Path path) throws IOException {
    final Path result;
    // Get the extension
    final String fileName = path.getFileName().toString();
    final String loweredFileName = fileName.toLowerCase(Locale.ENGLISH);
    if (loweredFileName.endsWith(".gz")) {
        String tempFileName = fileName.substring(0, loweredFileName.indexOf(".gz"));
        final int index = tempFileName.lastIndexOf('.');
        if (index > 0) {
            result = Files.createTempFile(tempFileName.substring(0, index),
                    tempFileName.substring(index, tempFileName.length()));
        } else {//from   w  w w  .j ava  2 s.  co m
            result = Files.createTempFile(tempFileName.substring(0, index), "");
        }
        try (final CompressorInputStream in = new CompressorStreamFactory()
                .createCompressorInputStream(new BufferedInputStream(Files.newInputStream(path)))) {
            Files.copy(in, result, StandardCopyOption.REPLACE_EXISTING);
        } catch (CompressorException e) {
            throw new IOException(e);
        }
    } else {
        result = path;
    }
    return result;
}

From source file:edu.pitt.dbmi.ccd.queue.service.AlgorithmQueueService.java

@Async
public Future<Void> runAlgorithmFromQueue(JobQueueInfo jobQueueInfo) {
    Long queueId = jobQueueInfo.getId();
    String fileName = jobQueueInfo.getFileName() + ".txt";
    String jsonFileName = jobQueueInfo.getFileName() + ".json";
    String commands = jobQueueInfo.getCommands();
    String tmpDirectory = jobQueueInfo.getTmpDirectory();
    String outputDirectory = jobQueueInfo.getOutputDirectory();

    List<String> cmdList = new LinkedList<>();
    cmdList.addAll(Arrays.asList(commands.split(";")));

    cmdList.add("--out");
    cmdList.add(tmpDirectory);// ww  w .ja v a 2s.c om

    StringBuilder sb = new StringBuilder();
    cmdList.forEach(cmd -> {
        sb.append(cmd);
        sb.append(" ");
    });
    LOGGER.info("Algorithm command: " + sb.toString());

    String errorFileName = String.format("error_%s", fileName);
    Path error = Paths.get(tmpDirectory, errorFileName);
    Path errorDest = Paths.get(outputDirectory, errorFileName);
    Path src = Paths.get(tmpDirectory, fileName);
    Path dest = Paths.get(outputDirectory, fileName);
    Path json = Paths.get(tmpDirectory, jsonFileName);
    Path jsonDest = Paths.get(outputDirectory, jsonFileName);

    try {
        ProcessBuilder pb = new ProcessBuilder(cmdList);
        pb.redirectError(error.toFile());
        Process process = pb.start();

        //Get process Id
        Long pid = Processes.processId(process);
        JobQueueInfo queuedJobInfo = jobQueueInfoService.findOne(queueId);
        LOGGER.info("Set Job's pid to be: " + pid);
        queuedJobInfo.setPid(pid);
        jobQueueInfoService.saveJobIntoQueue(queuedJobInfo);

        process.waitFor();

        if (process.exitValue() == 0) {
            LOGGER.info(String.format("Moving txt file %s to %s", src, dest));
            Files.move(src, dest, StandardCopyOption.REPLACE_EXISTING);
            LOGGER.info(String.format("Moving json file %s to %s", json, dest));
            Files.move(json, jsonDest, StandardCopyOption.REPLACE_EXISTING);
            Files.deleteIfExists(error);
        } else {
            LOGGER.info(String.format("Deleting tmp txt file %s", src));
            Files.deleteIfExists(src);
            LOGGER.info(String.format("Moving error file %s to %s", error, errorDest));
            Files.move(error, errorDest, StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (IOException | InterruptedException exception) {
        LOGGER.error("Algorithm did not run successfully.", exception);
    }

    LOGGER.info("Delete Job ID from queue: " + queueId);
    jobQueueInfoService.deleteJobById(queueId);

    return new AsyncResult<>(null);
}

From source file:org.structr.media.SetMetadataProcess.java

@Override
public Void processExited(int exitCode) {

    if (exitCode == 0) {

        try (final Tx tx = StructrApp.getInstance(securityContext).tx()) {

            // move converted file into place
            final java.io.File diskFile = new java.io.File(outputFileName + "." + fileExtension);
            final java.io.File dstFile = new java.io.File(outputFileName);
            if (diskFile.exists()) {

                Files.move(diskFile.toPath(), dstFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                FileHelper.updateMetadata(inputVideo);
            }//from  w w  w  .j  a  v  a 2 s.c o  m

            tx.success();

        } catch (FrameworkException | IOException fex) {
            fex.printStackTrace();
        }

    }

    return null;
}

From source file:org.zanata.sync.jobs.cache.RepoCacheImpl.java

private long copyDir(Path source, Path target) throws IOException {
    Files.createDirectories(target);
    AtomicLong totalSize = new AtomicLong(0);
    Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
            new SimpleFileVisitor<Path>() {
                @Override//from  w  ww.  j  a  va 2s  .  c  o  m
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    Path targetdir = target.resolve(source.relativize(dir));
                    try {
                        if (Files.isDirectory(targetdir) && Files.exists(targetdir)) {
                            return CONTINUE;
                        }
                        Files.copy(dir, targetdir, StandardCopyOption.REPLACE_EXISTING,
                                StandardCopyOption.COPY_ATTRIBUTES);
                    } catch (FileAlreadyExistsException e) {
                        if (!Files.isDirectory(targetdir)) {
                            throw e;
                        }
                    }
                    return CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (Files.isRegularFile(file)) {
                        totalSize.accumulateAndGet(Files.size(file), (l, r) -> l + r);
                    }
                    Path targetFile = target.resolve(source.relativize(file));

                    // only copy to target if it doesn't exist or it exist but the content is different
                    if (!Files.exists(targetFile)
                            || !com.google.common.io.Files.equal(file.toFile(), targetFile.toFile())) {
                        Files.copy(file, targetFile, StandardCopyOption.REPLACE_EXISTING,
                                StandardCopyOption.COPY_ATTRIBUTES);
                    }
                    return CONTINUE;
                }
            });
    return totalSize.get();
}

From source file:ml.dmlc.xgboost4j.java.NativeLibrary.java

private static File extract(String libPath, ClassLoader classLoader)
        throws IOException, IllegalArgumentException {

    // Split filename to prefix and suffix (extension)
    String filename = libPath.substring(libPath.lastIndexOf('/') + 1);
    int lastDotIdx = filename.lastIndexOf('.');
    String prefix = "";
    String suffix = null;/*from  www  .  j  a va  2  s .  c o  m*/
    if (lastDotIdx >= 0 && lastDotIdx < filename.length() - 1) {
        prefix = filename.substring(0, lastDotIdx);
        suffix = filename.substring(lastDotIdx);
    }

    // Prepare temporary file
    File temp = File.createTempFile(prefix, suffix);
    temp.deleteOnExit();

    // Open and check input stream
    InputStream is = classLoader.getResourceAsStream(libPath);
    if (is == null) {
        throw new FileNotFoundException("File " + libPath + " was not found inside JAR.");
    }

    // Open output stream and copy data between source file in JAR and the temporary file
    try {
        Files.copy(is, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } finally {
        is.close();
    }

    return temp;
}