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:org.azyva.dragom.test.integration.IntegrationTestSuite.java

/**
 * Resets the test workspace./* w w w.  j av a2 s  .c o m*/
 */
public static void resetTestWorkspace() {
    InputStream inputStreamLoggingProperties;
    Path pathLoggingProperties;
    String loggingProperties;

    System.out.println("Resetting test workspace directory " + IntegrationTestSuite.pathTestWorkspace + '.');

    try {
        LogManager.getLogManager().reset();

        if (IntegrationTestSuite.pathTestWorkspace.toFile().exists()) {
            Path pathModel;
            InputStream inputStream;

            pathModel = IntegrationTestSuite.pathTestWorkspace.resolve("simple-model.xml");
            inputStream = IntegrationTestSuite.class.getResourceAsStream("/simple-model.xml");
            Files.copy(inputStream, pathModel, StandardCopyOption.REPLACE_EXISTING);
            inputStream.close();

            System.setProperty("org.azyva.dragom.init-property.URL_MODEL", pathModel.toUri().toString());

            try {
                ExecContextManagerTool.main(new String[] {
                        "--workspace=" + IntegrationTestSuite.pathTestWorkspace.resolve("workspace"),
                        "release" });
            } catch (ExitException ee) {
                if (ee.status != 0) {
                    throw ee;
                }
            }

            FileUtils.deleteDirectory(IntegrationTestSuite.pathTestWorkspace.toFile());

            System.getProperties().remove("org.azyva.dragom.init-property.URL_MODEL");
        }

        IntegrationTestSuite.pathTestWorkspace.toFile().mkdirs();

        inputStreamLoggingProperties = IntegrationTestSuite.class.getResourceAsStream("/logging.properties");
        pathLoggingProperties = IntegrationTestSuite.pathTestWorkspace.resolve("logging.properties");
        Files.copy(inputStreamLoggingProperties, pathLoggingProperties, StandardCopyOption.REPLACE_EXISTING);
        inputStreamLoggingProperties.close();
        loggingProperties = FileUtils.readFileToString(pathLoggingProperties.toFile());
        loggingProperties = loggingProperties.replace("%test-workspace%",
                IntegrationTestSuite.pathTestWorkspace.toString());
        FileUtils.write(pathLoggingProperties.toFile(), loggingProperties);
        inputStreamLoggingProperties = new FileInputStream(pathLoggingProperties.toFile());
        LogManager.getLogManager().readConfiguration(inputStreamLoggingProperties);
        inputStreamLoggingProperties.close();
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:org.nuxeo.github.Analyzer.java

/**
 * @return true if there are unsigned contributors
 *//*from w ww.  ja  v  a  2  s .co m*/
protected boolean saveAndPrint() {
    Set<Developer> allContributors = new TreeSet<>();
    allContributors.addAll(developersByLogin.values());
    allContributors.addAll(developersByName.values());
    log.info(String.format("Found %s contributors", allContributors.size()));
    if (output == null) {
        output = Paths.get(System.getProperty("java.io.tmpdir"), "contributors.csv");
    }
    boolean unsigned = false;
    Path tmpFile;
    try {
        tmpFile = Files.createTempFile("contributors", ".csv");
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return false;
    }
    try (CSVWriter writer = new CSVWriter(Files.newBufferedWriter(tmpFile, Charset.defaultCharset()), '\t')) {
        writer.writeNext(CSV_HEADER);
        for (Developer dev : allContributors) {
            if (!unsigned && dev.getAliases().isEmpty() && !"Nuxeo".equalsIgnoreCase(dev.getCompany())
                    && !dev.isSigned()) {
                unsigned = true;
            }
            log.debug(dev);
            writer.writeNext(new String[] { dev.getLogin(), dev.getName(), Boolean.toString(dev.isSigned()),
                    setToString(dev.getEmails()), dev.getCompany(), dev.getUrl(), setToString(dev.getAliases()),
                    dev.isSigned() || "Nuxeo".equalsIgnoreCase(dev.getCompany())
                            || "ex-Nuxeo".equalsIgnoreCase(dev.getCompany()) ? ""
                                    : commitsToString(dev.getCommits()) });
        }
        Files.copy(tmpFile, output, StandardCopyOption.REPLACE_EXISTING);
        Files.delete(tmpFile);
        log.info("Saved to file: " + output);
    } catch (IOException e) {
        log.error("See " + tmpFile + System.lineSeparator() + e.getMessage(), e);
    }
    return unsigned;
}

From source file:org.roda.core.storage.fs.FSUtils.java

/**
 * Copies a directory/file from one path to another
 * //from w ww. j a  va  2s. c  om
 * @param sourcePath
 *          source path
 * @param targetPath
 *          target path
 * @param replaceExisting
 *          true if the target directory/file should be replaced if it already
 *          exists; false otherwise
 * @throws AlreadyExistsException
 * @throws GenericException
 */
public static void copy(final Path sourcePath, final Path targetPath, boolean replaceExisting)
        throws AlreadyExistsException, GenericException {

    // check if we can replace existing
    if (!replaceExisting && FSUtils.exists(targetPath)) {
        throw new AlreadyExistsException("Cannot copy because target path already exists: " + targetPath);
    }

    // ensure parent directory exists or can be created
    try {
        if (targetPath != null) {
            Files.createDirectories(targetPath.getParent());
        }
    } catch (IOException e) {
        throw new GenericException("Error while creating target directory parent folder", e);
    }

    if (FSUtils.isDirectory(sourcePath)) {
        try {
            Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs)
                        throws IOException {
                    Files.createDirectories(targetPath.resolve(sourcePath.relativize(dir)));
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                        throws IOException {
                    Files.copy(file, targetPath.resolve(sourcePath.relativize(file)));
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            throw new GenericException("Error while copying one directory into another", e);
        }
    } else {
        try {

            CopyOption[] copyOptions = replaceExisting
                    ? new CopyOption[] { StandardCopyOption.REPLACE_EXISTING }
                    : new CopyOption[] {};
            Files.copy(sourcePath, targetPath, copyOptions);
        } catch (IOException e) {
            throw new GenericException("Error while copying one file into another", e);
        }

    }

}

From source file:de.elomagic.maven.http.HTTPMojo.java

private void handleResponse(final Response response) throws Exception {
    HttpResponse httpResponse = response.returnResponse();
    StatusLine statusLine = httpResponse.getStatusLine();
    int statusCode = statusLine.getStatusCode();

    if (statusCode < 200 || statusCode > 299) {
        if (httpResponse.getEntity() != null) {
            getLog().info(EntityUtils.toString(httpResponse.getEntity()));
        } else {/*ww w . ja v a 2 s .c o  m*/
            getLog().info("Response body is empty.");
        }

        throw new Exception("Response status code " + statusCode + ": " + statusLine.getReasonPhrase());
    }

    getLog().info("Response status code " + statusCode + ": " + statusLine.getReasonPhrase());

    HttpEntity entity = httpResponse.getEntity();
    if (entity == null) {
        getLog().info("Response body is empty.");
    } else if (unpack) {
        File downloadedFile = File.createTempFile("mvn_http_plugin_", ".tmp");
        try (InputStream in = entity.getContent()) {
            Files.copy(in, downloadedFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

            if (StringUtils.isNoneBlank(digest)) {
                checkFile(downloadedFile.toPath());
            }

            getLog().info("Downloaded file size: "
                    + FileUtils.byteCountToDisplaySize(new Long(downloadedFile.length()).intValue()));

            unzipToFile(downloadedFile, outputDirectory);
        } finally {
            downloadedFile.delete();
        }
    } else if (toFile != null) {
        try (InputStream in = entity.getContent()) {
            Files.copy(in, toFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }

        if (StringUtils.isNoneBlank(digest)) {
            checkFile(toFile.toPath());
        }

        getLog().debug("Downloaded file location: " + toFile);
        getLog().debug("Downloaded file size: "
                + FileUtils.byteCountToDisplaySize(new Long(toFile.length()).intValue()));
    } else if (printResponse) {
        getLog().info("Response content: " + IOUtil.toString(entity.getContent(), "utf-8"));
    }
}

From source file:hydrograph.ui.dataviewer.actions.ReloadAction.java

private int copyCSVDebugFileAtDataViewerDebugFileLocation(String csvDebugFileLocation,
        String dataViewerFileAbsolutePath) {
    try {/*from  w w w  .  j  ava  2 s  . co  m*/
        Files.copy(Paths.get(csvDebugFileLocation), Paths.get(dataViewerFileAbsolutePath),
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        logger.error("unable to copy Debug csv file to data viewer file location", e);
        Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e);
        showDetailErrorMessage(Messages.UNABLE_TO_RELOAD_DEBUG_FILE
                + ": Unable to copy Debug csv file to data viewer file location", status);
        return StatusConstants.ERROR;
    }
    return StatusConstants.SUCCESS;
}

From source file:codes.thischwa.c5c.DispatcherPUT.java

private Path saveTemp(InputStream in, String name) throws IOException {
    String baseName = FilenameUtils.getBaseName(name);
    String ext = FilenameUtils.getExtension(name);
    try {//from  w w w  .  j  a  v  a 2 s .  c  o  m
        Path tempPath = Files.createTempFile(UserObjectProxy.getTempDirectory(), baseName, "." + ext);
        Files.copy(in, tempPath, StandardCopyOption.REPLACE_EXISTING);
        return tempPath;
    } catch (IOException e) {
        throw e;
    } finally {
        IOUtils.closeQuietly(in);
    }

}

From source file:org.apache.tika.eval.reports.ResultsReporter.java

private static Path getDefaultReportsConfig(Connection c) throws IOException, SQLException {
    DatabaseMetaData md = c.getMetaData();
    String internalPath = null;//from www. ja v a2 s.  c o m
    try (ResultSet rs = md.getTables(null, null, "%", null)) {
        while (rs.next()) {
            String tName = rs.getString(3);
            if (ExtractComparer.CONTENTS_TABLE_B.getName().equalsIgnoreCase(tName)) {
                internalPath = "/comparison-reports.xml";
                break;
            } else if (ExtractProfiler.PROFILE_TABLE.getName().equalsIgnoreCase(tName)) {
                internalPath = "/profile-reports.xml";
                break;
            }
        }
    }

    if (internalPath == null) {
        throw new RuntimeException("Couldn't determine if this database was a 'profiler' or 'comparison' db");
    }
    Path tmp = Files.createTempFile("tmp-tika-reports", ".xml");
    Files.copy(ResultsReporter.class.getResourceAsStream(internalPath), tmp,
            StandardCopyOption.REPLACE_EXISTING);
    return tmp;
}

From source file:com.github.podd.resources.test.AbstractResourceImplTest.java

/**
 * Builds a {@link Representation} from a Resource.
 *
 * @param resourcePath/*from  w w  w  .  jav a 2 s.  com*/
 * @param mediaType
 * @return
 * @throws IOException
 */
protected FileRepresentation buildRepresentationFromResource(final String resourcePath,
        final MediaType mediaType) throws IOException {
    final Path target = this.testDir
            .resolve(UUID.randomUUID().toString() + "." + Paths.get(resourcePath).getFileName());

    try (final InputStream input = this.getClass().getResourceAsStream(resourcePath)) {
        Files.copy(input, target, StandardCopyOption.REPLACE_EXISTING);
    }

    final FileRepresentation fileRep = new FileRepresentation(target.toFile(), mediaType);
    return fileRep;
}

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

public synchronized Collection<ArduinoPlatform> getPlatformUpdates(IProgressMonitor monitor)
        throws CoreException {
    List<ArduinoPlatform> platforms = new ArrayList<>();
    URL[] urls = ArduinoPreferences.getBoardUrlList();
    SubMonitor sub = SubMonitor.convert(monitor, urls.length + 1);

    sub.beginTask("Downloading package descriptions", urls.length); //$NON-NLS-1$
    for (URL url : urls) {
        Path packagePath = ArduinoPreferences.getArduinoHome().resolve(Paths.get(url.getPath()).getFileName());
        try {/*from   ww w . j  a v a 2 s .  c  o m*/
            Files.createDirectories(ArduinoPreferences.getArduinoHome());
            try (InputStream in = url.openStream()) {
                Files.copy(in, packagePath, StandardCopyOption.REPLACE_EXISTING);
            }
        } catch (IOException e) {
            throw Activator.coreException(String.format("Error loading %s", url.toString()), e); //$NON-NLS-1$
        }
        sub.worked(1);
    }

    sub.beginTask("Loading available package updates", 1); //$NON-NLS-1$
    resetPackages();
    for (ArduinoPackage pkg : getPackages()) {
        platforms.addAll(pkg.getPlatformUpdates());
    }
    sub.done();

    return platforms;
}

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

private void remoteCopy(Path source, Path target, CopyOption... options) throws IOException {
    Configuration configuration = getConfiguration();
    Path tmp = target.getParent();
    Path dest = null;/*ww  w  .  j a  v  a  2  s.c  om*/
    do {
        dest = tmp.resolve(String.format("tmp%s/", System.currentTimeMillis()));
    } while (Files.exists(dest));
    try {
        DistCpOptions distCpOptions = new DistCpOptions(
                Arrays.asList(((HadoopFileSystemPath) source).getPath()),
                ((HadoopFileSystemPath) dest).getPath());
        List<CopyOption> optionList = Arrays.asList(options);

        distCpOptions.setOverwrite(optionList.contains(StandardCopyOption.REPLACE_EXISTING));
        try {
            DistCp distCp = new DistCp(configuration, distCpOptions);
            Job job = distCp.execute();
            job.waitForCompletion(true);
        } catch (Exception e) {
            throw new IOException(e.getLocalizedMessage(), e);
        }
        move(dest.resolve(source.getFileName()), target, options);
    } finally {
        delete(dest, false);
    }

}