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:de.tiqsolutions.hdfs.HadoopFileSystemProvider.java

@Override
public void move(Path source, Path target, CopyOption... options) throws IOException {
    FileSystem fs = source.getFileSystem();
    if (!HadoopFileSystem.class.isInstance(fs))
        throw new IllegalArgumentException("source");
    if (!fs.provider().equals(target.getFileSystem().provider()))
        throw new ProviderMismatchException();
    List<Rename> renameOptions = new ArrayList<>();
    List<CopyOption> copyOptions = Arrays.asList(options);

    if (copyOptions.contains(StandardCopyOption.REPLACE_EXISTING))
        renameOptions.add(Rename.OVERWRITE);
    try {//w  ww.  j av  a  2s.  com
        ((HadoopFileSystem) fs).getFileContext().rename(((HadoopFileSystemPath) source).getPath(),
                ((HadoopFileSystemPath) target).getPath(),
                renameOptions.toArray(new Rename[renameOptions.size()]));
    } catch (RemoteException e) {
        rethrowRemoteException(e, source, target);

    }
}

From source file:pl.nask.hsn2.task.CuckooTask.java

private Path copyToTempFile(InputStream is) throws IOException {
    Path tempFile = Files.createTempFile(jobContext.getJobId() + "_" + jobContext.getReqId(), "_cuckoo_pcap");
    Files.copy(is, tempFile, StandardCopyOption.REPLACE_EXISTING);
    is.close();//from  ww  w.j  a va 2  s.  co  m
    return tempFile;
}

From source file:it.baeyens.arduino.managers.Manager.java

/**
 * downloads an archive file from the internet and saves it in the download
 * folder under the name "pArchiveFileName" then extrats the file to
 * pInstallPath if pForceDownload is true the file will be downloaded even
 * if the download file already exists if pForceDownload is false the file
 * will only be downloaded if the download file does not exists The
 * extraction is done with processArchive so only files types supported by
 * this method will be properly extracted
 * /*from   w w  w.  j  a va2 s  .  c  o  m*/
 * @param pURL
 *            the url of the file to download
 * @param pArchiveFileName
 *            the name of the file in the download folder
 * @param pInstallPath
 * @param pForceDownload
 * @param pMonitor
 * @return
 */
public static IStatus downloadAndInstall(String pURL, String pArchiveFileName, Path pInstallPath,
        boolean pForceDownload, IProgressMonitor pMonitor) {
    IPath dlDir = ConfigurationPreferences.getInstallationPathDownload();
    IPath archivePath = dlDir.append(pArchiveFileName);
    String archiveFullFileName = archivePath.toString();
    try {
        URL dl = new URL(pURL);
        dlDir.toFile().mkdir();
        if (!archivePath.toFile().exists() || pForceDownload) {
            pMonitor.subTask("Downloading " + pArchiveFileName + " .."); //$NON-NLS-1$ //$NON-NLS-2$
            Files.copy(dl.openStream(), Paths.get(archivePath.toString()), StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (IOException e) {
        return new Status(IStatus.ERROR, Activator.getId(), Messages.Manager_Failed_to_download + pURL, e);
    }
    return processArchive(pArchiveFileName, pInstallPath, pForceDownload, archiveFullFileName, pMonitor);
}

From source file:org.ballerinalang.containers.docker.impl.DefaultBallerinaDockerClient.java

private Path prepTempDockerfileContext() throws IOException, BallerinaDockerClientException {
    // TODO: Until the tmp.dir modification is removed from ballerina-launcher
    String tmpDirLocation = System.getProperty(TMPDIR_SYSTEM_PROP);
    String ballerinaVersion = System.getProperty(BALLERINA_VERSION_SYSTEM_PROP);
    if (tmpDirLocation != null) {
        File tmpDirFile = new File(tmpDirLocation);
        if (!tmpDirFile.exists() && !tmpDirFile.mkdirs()) {
            throw new BallerinaDockerClientException("Couldn't create temporary directory: " + tmpDirLocation);
        }//from  w  ww .  ja v  a  2  s  .c  om
        // Set Fabric8 docker-client temp directory since the default "/tmp" does not work on Windows
        System.setProperty(DOCKER_CLIENT_TMPDIR_SYSTEM_PROP, tmpDirLocation);
    }

    if (ballerinaVersion == null) {
        throw new BallerinaDockerClientException(
                "[ERROR] System Property '" + BALLERINA_VERSION_SYSTEM_PROP + "' is not defined. ");
    }

    String tempDirName = PATH_TEMP_DOCKERFILE_CONTEXT_PREFIX + String.valueOf(Instant.now().getEpochSecond());
    Path tmpDir = Files.createTempDirectory(tempDirName);
    Files.createDirectory(Paths.get(tmpDir.toString() + File.separator + PATH_FILES));
    InputStream in = getClass().getResourceAsStream(PATH_DOCKER_IMAGE_ROOT + PATH_DOCKERFILE_NAME);

    Files.copy(in, Paths.get(tmpDir.toString() + File.separator + PATH_DOCKERFILE_NAME),
            StandardCopyOption.REPLACE_EXISTING);

    // Replace ${BALLERINA_VERSION} with ballerinaVersion
    Path path = Paths.get(tmpDir.toString() + File.separator + PATH_DOCKERFILE_NAME);
    Charset charset = StandardCharsets.UTF_8;

    String content = new String(Files.readAllBytes(path), charset);
    content = content.replaceAll("BALLERINA_VERSION", ballerinaVersion);
    Files.write(path, content.getBytes(charset));

    return tmpDir;
}

From source file:org.caleydo.data.importer.tcga.FirehoseProvider.java

private TCGAFileInfo extractFileFromTarGzArchive(URL inUrl, String fileToExtract, File outputDirectory,
        boolean hasTumor) {
    log.info(inUrl + " download and extract: " + fileToExtract);
    File targetFile = new File(outputDirectory, fileToExtract);

    // use cached
    if (targetFile.exists() && !settings.isCleanCache()) {
        log.fine(inUrl + " cache hit");
        return new TCGAFileInfo(targetFile, inUrl, fileToExtract);
    }//from www  .  j  a  v a  2 s  .co  m

    File notFound = new File(outputDirectory, fileToExtract + "-notfound");
    if (notFound.exists() && !settings.isCleanCache()) {
        log.warning(inUrl + " marked as not found");
        return null;
    }

    String alternativeName = fileToExtract;
    if (hasTumor) {
        alternativeName = "/" + tumor.getBaseName() + fileToExtract;
        fileToExtract = "/" + tumor + fileToExtract;
    }

    TarArchiveInputStream tarIn = null;
    OutputStream out = null;
    try {
        InputStream in = new BufferedInputStream(inUrl.openStream());

        // ok we have the file
        tarIn = new TarArchiveInputStream(new GZIPInputStream(in));

        // search the correct entry
        ArchiveEntry act = tarIn.getNextEntry();
        while (act != null && !act.getName().endsWith(fileToExtract)
                && !act.getName().endsWith(alternativeName)) {
            act = tarIn.getNextEntry();
        }
        if (act == null) // no entry found
            throw new FileNotFoundException("no entry named: " + fileToExtract + " found");

        byte[] buf = new byte[4096];
        int n;
        targetFile.getParentFile().mkdirs();
        // use a temporary file to recognize if we have aborted between run
        String tmpFile = targetFile.getAbsolutePath() + ".tmp";
        out = new BufferedOutputStream(new FileOutputStream(tmpFile));
        while ((n = tarIn.read(buf, 0, 4096)) > -1)
            out.write(buf, 0, n);
        out.close();
        Files.move(new File(tmpFile).toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

        log.info(inUrl + " extracted " + fileToExtract);
        return new TCGAFileInfo(targetFile, inUrl, fileToExtract);
    } catch (FileNotFoundException e) {
        log.log(Level.WARNING, inUrl + " can't extract" + fileToExtract + ": file not found", e);
        // file was not found, create a marker to remember this for quicker checks
        notFound.getParentFile().mkdirs();
        try {
            notFound.createNewFile();
        } catch (IOException e1) {
            log.log(Level.WARNING, inUrl + " can't create not-found marker", e);
        }
        return null;
    } catch (Exception e) {
        log.log(Level.SEVERE, inUrl + " can't extract" + fileToExtract + ": " + e.getMessage(), e);
        return null;
    } finally {
        Closeables.closeQuietly(tarIn);
        Closeables.closeQuietly(out);
    }
}

From source file:nl.coinsweb.sdk.FileManager.java

public static Path placeAttachment(String internalRef, Path attachment) {
    Path fileName = attachment.getFileName();
    Path homePath = getTempZipPath().resolve(internalRef);
    Path attachmentPath = homePath.resolve(ATTACHMENT_PATH);
    Path absoluteTempPath = attachmentPath.resolve(fileName);
    try {//from   www  .  j a  v  a2s  . c  o m
        Files.copy(attachment, absoluteTempPath, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
    return absoluteTempPath;
}

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

@Override
public void replace(String backendPath, InputStream in) throws C5CException {
    Path file = buildRealPath(backendPath);
    try {/*from   w w w.jav  a  2  s  .  c o  m*/
        Files.copy(in, file, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new FilemanagerException(FilemanagerAction.REPLACE, FilemanagerException.Key.InvalidFileUpload,
                file.getFileName().toString());
    }
}

From source file:de.cebitec.readXplorer.differentialExpression.plot.DeSeqGraphicsTopComponent.java

private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
    ReadXplorerFileChooser fc = new ReadXplorerFileChooser(new String[] { "svg" }, "svg") {
        private static final long serialVersionUID = 1L;

        @Override//from  w w  w  .  ja va  2 s  . c  o m
        public void save(String fileLocation) {
            ProgressHandle progressHandle = ProgressHandleFactory
                    .createHandle("Save plot to svg file: " + fileLocation);
            Path to = FileSystems.getDefault().getPath(fileLocation, "");
            DeSeqAnalysisHandler.Plot selectedPlot = (DeSeqAnalysisHandler.Plot) plotType.getSelectedItem();
            if (selectedPlot == DeSeqAnalysisHandler.Plot.MAplot) {
                saveToSVG(fileLocation);
            } else {
                Path from = currentlyDisplayed.toPath();
                try {
                    Path outputFile = Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
                    messages.setText("SVG image saved to " + outputFile.toString());
                } catch (IOException ex) {
                    Date currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
                    Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "{0}: " + ex.getMessage(),
                            currentTimestamp);
                    JOptionPane.showMessageDialog(null, ex.getMessage(), "Could not write to file.",
                            JOptionPane.WARNING_MESSAGE);
                } finally {
                    progressHandle.switchToDeterminate(100);
                    progressHandle.finish();
                }
            }
        }

        @Override
        public void open(String fileLocation) {
        }
    };
    fc.openFileChooser(ReadXplorerFileChooser.SAVE_DIALOG);
}

From source file:com.upplication.s3fs.util.AmazonS3ClientMock.java

@Override
public CopyObjectResult copyObject(String sourceBucketName, String sourceKey, String destinationBucketName,
        String destinationKey) throws AmazonClientException {
    Path src = find(sourceBucketName, sourceKey);
    if (src != null && Files.exists(src)) {
        Path bucket = find(destinationBucketName);
        Path dest = bucket.resolve(destinationKey.replaceAll("/", "%2F"));
        try {//from   ww w.  j a va 2  s.c  om
            Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new AmazonServiceException("Problem copying mock objects: ", e);
        }

        return new CopyObjectResult();
    }

    throw new AmazonServiceException("object source not found");
}

From source file:de.dentrassi.build.apt.repo.AptWriter.java

private void copyArtifact(final Component component, final File packageFile, final BinaryPackagePackagesFile cf)
        throws IOException {
    final String name = cf.get("Package");

    final File targetFile = makeTargetFile(component, packageFile, name);
    this.console.info("Copy artifact: " + targetFile);
    targetFile.mkdirs();/*from www  . jav  a2  s. c  o  m*/
    Files.copy(packageFile.toPath(), targetFile.toPath(), StandardCopyOption.COPY_ATTRIBUTES,
            StandardCopyOption.REPLACE_EXISTING);
}