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.forgerock.openidm.maintenance.upgrade.FileStateCheckerTest.java

@Test
public void testUpdateStateNoChange() throws IOException, URISyntaxException, NoSuchAlgorithmException {
    Files.copy(Paths.get(getClass().getResource("/checksums.csv").toURI()), tempFile,
            StandardCopyOption.REPLACE_EXISTING);
    ChecksumFile tempChecksumFile = new ChecksumFile(tempFile);
    FileStateChecker checker = new FileStateChecker(tempChecksumFile);
    Path filepath = Paths.get("file1");
    checker.updateState(filepath);//  w  ww  . j  a  v  a 2 s .c  o m
    checker = new FileStateChecker(tempChecksumFile);
    assertThat(checker.getCurrentFileState(filepath).equals(FileState.UNCHANGED));
}

From source file:com.netflix.nicobar.core.persistence.ArchiveRepositoryTest.java

@BeforeClass
public void setup() throws Exception {
    URL testJarUrl = getClass().getClassLoader().getResource(TEST_MODULE_SPEC_JAR.getResourcePath());
    if (testJarUrl == null) {
        fail("Couldn't locate " + TEST_MODULE_SPEC_JAR.getResourcePath());
    }// ww  w  . j  a v  a  2s.co m
    testArchiveJarFile = Files.createTempFile(TEST_MODULE_SPEC_JAR.getModuleId().toString(), ".jar");
    InputStream inputStream = testJarUrl.openStream();
    Files.copy(inputStream, testArchiveJarFile, StandardCopyOption.REPLACE_EXISTING);
    IOUtils.closeQuietly(inputStream);
}

From source file:org.ulyssis.ipp.publisher.FileOutput.java

@Override
public void outputScore(Score score) {
    Path tmpFile = null;/*from  ww  w  . j a  v  a 2s.  co  m*/
    try {
        if (tmpDir.isPresent()) {
            tmpFile = Files.createTempFile(tmpDir.get(), "score-", ".json",
                    PosixFilePermissions.asFileAttribute(defaultPerms));
        } else {
            tmpFile = Files.createTempFile("score-", ".json",
                    PosixFilePermissions.asFileAttribute(defaultPerms));
        }
        BufferedWriter writer = Files.newBufferedWriter(tmpFile, StandardCharsets.UTF_8);
        Serialization.getJsonMapper().writer(new DefaultPrettyPrinter()).writeValue(writer, score);
        Files.move(tmpFile, filePath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        LOG.error("Error writing score to file!", e);
    } finally {
        try {
            if (tmpFile != null)
                Files.deleteIfExists(tmpFile);
        } catch (IOException ignored) {
        }
    }
}

From source file:org.wso2.security.tool.util.FileHandler.java

/**
 * Saves the uploaded files by the client.
 * Temporarily saves the files uploaded by the clients in the system's tempdir.
 *
 * @param fileInputStream The uploaded file InputStream.
 * @param fileInfo        The details about the uploaded file.
 * @throws FeedbackToolException If an Exception is thrown inside the method implementation.
 *///from  www  .ja  v a 2  s .  c  o m
public static String saveUploadedFile(InputStream fileInputStream, FileInfo fileInfo)
        throws FeedbackToolException {
    try {
        Files.copy(fileInputStream, Paths.get(System.getProperty("java.io.tmpdir"), fileInfo.getFileName()),
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new FeedbackToolException(
                "IOException was thrown while saving the file: " + fileInfo.getFileName(), e);
    }
    return Paths.get(System.getProperty("java.io.tmpdir"), fileInfo.getFileName()).toString();
}

From source file:squash.deployment.lambdas.utils.FileUtils.java

/**
 * GZIPs files in-place.//w w w  .  j a v a 2s  .  com
 * 
 * <p>Replaces files with their gzip-ed version, without altering the filename. The files can
 *    be a mix of files and folders. Any folders will be recursed into, gzip-ing contained
 *    files in-place. A list of paths to exclude from gzip-ing should also be provided.
 * 
 *    @param pathsToZip the list of paths to gzip.
 *    @param pathsToExclude the list of paths to exclude.
 *    @param logger a CloudwatchLogs logger.
 * @throws IOException 
 */
public static void gzip(List<File> pathsToZip, List<File> pathsToExclude, LambdaLogger logger)
        throws IOException {

    for (File pathToZip : pathsToZip) {
        logger.log("Replacing file with its gzip-ed version: " + pathToZip.getAbsolutePath());
        if (pathsToExclude.contains(pathToZip)) {
            continue;
        }
        if (pathToZip.isDirectory()) {
            logger.log("File is a directory - so recursing...");
            gzip(new ArrayList<File>(Arrays.asList(pathToZip.listFiles())), pathsToExclude, logger);
            continue;
        }

        // File is a file - so gzip it
        File tempZip = File.createTempFile("temp", ".gz", new File(pathToZip.getParent()));
        Files.deleteIfExists(tempZip.toPath());

        byte[] buffer = new byte[1024];
        try {
            try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(new FileOutputStream(tempZip))) {
                try (FileInputStream fileInputStream = new FileInputStream(pathToZip)) {
                    int len;
                    while ((len = fileInputStream.read(buffer)) > 0) {
                        gzipOutputStream.write(buffer, 0, len);
                    }
                }
                gzipOutputStream.finish();
            }
        } catch (IOException e) {
            logger.log("Caught exception whilst zipping file: " + e.getMessage());
            throw e;
        }

        // Replace original file with gzip-ed file, with same name
        Files.copy(tempZip.toPath(), pathToZip.toPath(), StandardCopyOption.REPLACE_EXISTING);
        Files.deleteIfExists(tempZip.toPath());
        logger.log("Replaced file with its gzip-ed version");
    }
}

From source file:org.apache.hadoop.hbase.client.TestUpdateConfiguration.java

@Test
public void testMasterOnlineConfigChange() throws IOException {
    LOG.debug("Starting the test");
    Path cnfPath = FileSystems.getDefault().getPath("target/test-classes/hbase-site.xml");
    Path cnf2Path = FileSystems.getDefault().getPath("target/test-classes/hbase-site2.xml");
    Path cnf3Path = FileSystems.getDefault().getPath("target/test-classes/hbase-site3.xml");
    // make a backup of hbase-site.xml
    Files.copy(cnfPath, cnf3Path, StandardCopyOption.REPLACE_EXISTING);
    // update hbase-site.xml by overwriting it
    Files.copy(cnf2Path, cnfPath, StandardCopyOption.REPLACE_EXISTING);

    Admin admin = TEST_UTIL.getHBaseAdmin();
    ServerName server = TEST_UTIL.getHBaseCluster().getMaster().getServerName();
    admin.updateConfiguration(server);//from  ww w .j a  v a 2 s . c  o  m
    Configuration conf = TEST_UTIL.getMiniHBaseCluster().getMaster().getConfiguration();
    int custom = conf.getInt("hbase.custom.config", 0);
    assertEquals(custom, 1000);
    // restore hbase-site.xml
    Files.copy(cnf3Path, cnfPath, StandardCopyOption.REPLACE_EXISTING);
}

From source file:com.ejisto.util.visitor.ConditionMatchingCopyFileVisitor.java

private void copy(Path srcFile) throws IOException {
    Path relative = options.srcRoot.relativize(srcFile);
    int count = relative.getNameCount();
    StringBuilder newFileName = new StringBuilder();
    if (count > 1) {
        newFileName.append(relative.getParent().toString());
        newFileName.append(File.separator);
    }/*from   www .j  a v  a2  s  .co  m*/
    newFileName.append(defaultString(options.filesPrefix)).append(srcFile.getFileName().toString());
    Files.copy(srcFile, options.targetRoot.resolve(newFileName.toString()),
            StandardCopyOption.REPLACE_EXISTING);
}

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

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

                @Override/*from   w w  w. j a v a 2  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);
                    data.addAll(parseFile(temp.toFile().getAbsolutePath()));
                    return FileVisitResult.CONTINUE;
                }

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

From source file:org.xwiki.job.internal.JobStatusSerializer.java

/**
 * @param status the status to serialize
 * @param file the file to serialize the status to
 * @throws IOException when failing to serialize the status
 *//*from w ww .j  a  v  a2 s .c om*/
public void write(JobStatus status, File file) throws IOException {
    File tempFile = File.createTempFile(file.getName(), ".tmp");

    FileOutputStream stream = FileUtils.openOutputStream(tempFile);

    try {
        write(status, stream);
    } finally {
        IOUtils.closeQuietly(stream);
    }

    // Copy the file in it's final destination
    file.mkdirs();
    Files.move(tempFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

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

public static Set<Word> parseZip(String zipFile) {
    Set<Word> data = new HashSet<>();
    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 ww w . ja va2 s  . co 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);
                    data.addAll(parseFile(temp.toFile().getAbsolutePath()));
                    return FileVisitResult.CONTINUE;
                }

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