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.kalypso.commons.resources.SetContentHelper.java

public void setFileContents(final IFile file, final boolean force, final boolean keepHistory,
        final IProgressMonitor monitor, final String charset) throws CoreException {
    final String oldCharset = findCurrentCharset(file);
    final String newCharset = findNewCharset(file, charset, oldCharset);

    final File javaFile = file.getLocation().toFile();

    // save file to backup
    final Path filePath = javaFile.toPath();

    final String fileName = javaFile.getAbsolutePath();
    final String backupFileName = fileName + BCKUP_SUFFIX + System.currentTimeMillis();
    final File backupFile = new File(backupFileName);

    try {//w  w w . j  av a 2  s  .c o  m
        writeContents(backupFile, newCharset, monitor);

        /* rename backup to new file */
        Files.move(backupFile.toPath(), filePath, StandardCopyOption.REPLACE_EXISTING);

        file.refreshLocal(IFile.DEPTH_ZERO, new NullProgressMonitor());

        if (newCharset != null && !ObjectUtils.equals(oldCharset, newCharset))
            file.setCharset(newCharset, new SubProgressMonitor(monitor, 1000));
    } catch (final Throwable e) {
        throw new CoreException(StatusUtilities.statusFromThrowable(e,
                Messages.getString("org.kalypso.commons.resources.SetContentHelper.2"))); //$NON-NLS-1$
    }

    // enclose in finally?
    monitor.done();
}

From source file:org.ballerinalang.stdlib.system.FileSystemTest.java

@Test(description = "Test for changing file path to already existing file path")
public void testFileRenameWithInvalidPath() throws IOException {
    try {/*from  w w w  .  j  ava 2  s  .  c  om*/
        Files.copy(srcFilePath, tempSourcePath, StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES);
        Files.copy(srcFilePath, tempDestPath, StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES);

        BValue[] args = { new BString(tempSourcePath.toString()), new BString(tempDestPath.toString()) };
        BValue[] returns = BRunUtil.invoke(compileResult, "testRename", args);
        assertTrue(returns[0] instanceof BError);
        BError error = (BError) returns[0];
        assertEquals(error.getReason(), "{ballerina/system}OPERATION_FAILED");
        log.info("Ballerina error: " + error.getDetails().stringValue());
    } finally {
        Files.deleteIfExists(tempSourcePath);
        Files.deleteIfExists(tempDestPath);
    }
}

From source file:org.discosync.ApplySyncPack.java

/**
 * Apply a syncpack to a target directory.
 *///from   ww w.j a v  a  2s  .co  m
protected void applySyncPack(String syncPackDir, String targetDir) throws SQLException, IOException {

    // read file operations from database
    File fileOpDbFile = new File(syncPackDir, "fileoperations");
    FileOperationDatabase db = new FileOperationDatabase(fileOpDbFile.getAbsolutePath());
    db.open();

    Iterator<FileListEntry> it = db.getFileListOperationIterator();

    Path syncFileBaseDir = Paths.get(syncPackDir, "files");
    String syncFileBaseDirStr = syncFileBaseDir.toAbsolutePath().toString();

    int filesCopied = 0;
    int filesReplaced = 0;
    int filesDeleted = 0;
    long copySize = 0L;
    long deleteSize = 0L;

    // Collect directories during processing.
    List<FileListEntry> directoryOperations = new ArrayList<>();

    // First process all files, then the directories
    while (it.hasNext()) {

        FileListEntry e = it.next();

        // Remember directories
        if (e.isDirectory()) {
            directoryOperations.add(e);
            continue;
        }

        String path = e.getPath();
        Path sourcePath = Paths.get(syncFileBaseDirStr, path); // may not exist
        Path targetPath = Paths.get(targetDir, path); // may not exist

        if (e.getOperation() == FileOperations.COPY) {
            // copy new file, target files should not exist
            if (Files.exists(targetPath)) {
                System.out
                        .println("Error: the file should not exist: " + targetPath.toAbsolutePath().toString());
            } else {
                if (!Files.exists(targetPath.getParent())) {
                    Files.createDirectories(targetPath.getParent());
                }

                Files.copy(sourcePath, targetPath);
                filesCopied++;
                copySize += e.getSize();
            }

        } else if (e.getOperation() == FileOperations.REPLACE) {
            // replace existing file
            if (!Files.exists(targetPath)) {
                System.out.println("Info: the file should exist: " + targetPath.toAbsolutePath().toString());
            }
            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
            filesReplaced++;
            copySize += e.getSize();

        } else if (e.getOperation() == FileOperations.DELETE) {
            // delete existing file
            if (!Files.exists(targetPath)) {
                System.out.println("Info: the file should exist: " + targetPath.toAbsolutePath().toString());
            } else {
                long fileSize = Files.size(targetPath);
                if (fileSize != e.getSize()) {
                    // show info, delete anyway
                    System.out.println(
                            "Info: the file size is different: " + targetPath.toAbsolutePath().toString());
                }
                deleteSize += fileSize;
                Files.delete(targetPath);
                filesDeleted++;
            }
        }
    }

    db.close();

    // Sort directory list to ensure directories are deleted bottom-up (first /dir1/dir2, then /dir1)
    Collections.sort(directoryOperations, new Comparator<FileListEntry>() {
        @Override
        public int compare(FileListEntry e1, FileListEntry e2) {
            return e2.getPath().compareTo(e1.getPath().toString());
        }
    });

    // Now process directories - create and delete empty directories
    for (FileListEntry e : directoryOperations) {

        String path = e.getPath();
        Path targetPath = Paths.get(targetDir, path); // may not exist

        if (e.getOperation() == FileOperations.COPY) {
            // create directory if needed
            if (!Files.exists(targetPath)) {
                Files.createDirectories(targetPath);
            }
        } else if (e.getOperation() == FileOperations.DELETE) {

            if (!Files.exists(targetPath)) {
                System.out.println(
                        "Info: Directory to DELETE does not exist: " + targetPath.toAbsolutePath().toString());

            } else if (!Files.isDirectory(targetPath, LinkOption.NOFOLLOW_LINKS)) {
                System.out.println("Info: Directory to DELETE is not a directory, but a file: "
                        + targetPath.toAbsolutePath().toString());

            } else if (!Utils.isDirectoryEmpty(targetPath)) {
                System.out.println("Info: Directory to DELETE is not empty, but should be empty: "
                        + targetPath.toAbsolutePath().toString());

            } else {
                // delete directory
                Files.delete(targetPath);
            }
        }
    }

    System.out.println("Apply of syncpack '" + syncPackDir + "' to directory '" + targetDir + "' finished.");
    System.out.println("Files copied  : " + String.format("%,d", filesCopied));
    System.out.println("Files replaced: " + String.format("%,d", filesReplaced));
    System.out.println("Files deleted : " + String.format("%,d", filesDeleted));
    System.out.println("Bytes copied  : " + String.format("%,d", copySize));
    System.out.println("Bytes deleted : " + String.format("%,d", deleteSize));
}

From source file:org.apache.jmeter.report.dashboard.TemplateVisitor.java

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

    // Depending on file extension, copy or process file
    String extension = FilenameUtils.getExtension(file.toString());
    if (TEMPLATED_FILE_EXT.equalsIgnoreCase(extension)) {
        // Process template file
        String templatePath = source.relativize(file).toString();
        Template template = configuration.getTemplate(templatePath);
        Path newPath = target.resolve(FilenameUtils.removeExtension(templatePath));
        try (FileOutputStream stream = new FileOutputStream(newPath.toString());
                Writer writer = new OutputStreamWriter(stream, StandardCharsets.UTF_8);
                BufferedWriter bufferedWriter = new BufferedWriter(writer)) {
            template.process(data, bufferedWriter);
        } catch (TemplateException ex) {
            throw new IOException(ex);
        }//from w  w w  .j  a  v a 2s  . c  o  m

    } else {
        // Copy regular file
        Path newFile = target.resolve(source.relativize(file));
        Files.copy(file, newFile, StandardCopyOption.REPLACE_EXISTING);
    }
    return FileVisitResult.CONTINUE;
}

From source file:org.wildfly.plugin.common.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));
        } else {//from   w  ww .ja v a2  s  . co m
            result = Files.createTempFile(tempFileName.substring(0, index), "");
        }
        try (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:com.netflix.nicobar.cassandra.CassandraArchiveRepositoryTest.java

@BeforeClass
public void setup() throws Exception {
    gateway = mock(CassandraGateway.class);
    Keyspace mockKeyspace = mock(Keyspace.class);
    when(mockKeyspace.getKeyspaceName()).thenReturn("testKeySpace");

    when(gateway.getKeyspace()).thenReturn(mockKeyspace);
    when(gateway.getColumnFamily()).thenReturn("testColumnFamily");

    config = new BasicCassandraRepositoryConfig.Builder(gateway).setRepositoryId("TestRepo")
            .setArchiveOutputDirectory(Files.createTempDirectory(this.getClass().getSimpleName() + "_"))
            .build();//from ww  w.  ja v a  2 s . co m
    repository = new CassandraArchiveRepository(config);

    URL testJarUrl = getClass().getClassLoader()
            .getResource(TestResource.TEST_HELLOWORLD_JAR.getResourcePath());
    if (testJarUrl == null) {
        fail("Couldn't locate " + TestResource.TEST_HELLOWORLD_JAR.getResourcePath());
    }
    testArchiveJarFile = Files.createTempFile(TestResource.TEST_HELLOWORLD_JAR.getModuleId().toString(),
            ".jar");
    InputStream inputStream = testJarUrl.openStream();
    Files.copy(inputStream, testArchiveJarFile, StandardCopyOption.REPLACE_EXISTING);
    IOUtils.closeQuietly(inputStream);
}

From source file:com.cyc.corpus.nlmpaper.AIMedOpenAccessPaper.java

private Optional<AIMedArticle> get() {
    if (paper != null) {
        return Optional.of(paper);
    }/*  w w  w .  j  a  va 2  s.c o m*/

    try {
        Optional<Path> xmlpath = getPaperPath();
        if (xmlpath.isPresent()) {
            Path destinationD = Paths.get(basedir, "AIMedOpenAccess", "XML");

            if (Files.notExists(destinationD, LinkOption.NOFOLLOW_LINKS)) {
                Files.createDirectory(destinationD);
            }

            Path extractTo = Paths.get(basedir, "AIMedOpenAccess", "XML",
                    xmlpath.get().getFileName().toString());

            Files.copy(xmlpath.get(), extractTo, StandardCopyOption.REPLACE_EXISTING);

            // specify the location and name of xml file to be read  
            File xmlFile = extractTo.toFile();
            String articleString = FileUtils.readFileToString(xmlFile).trim();
            paper = new AIMedArticle(articleString);

            return Optional.of(paper);
        }
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
        return Optional.empty();
    }

    return Optional.empty();
}

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

private void moveToExtLibDir(File file) throws IOException {
    Files.move(file.toPath(), Paths.get(extLib).resolve(file.getName()), StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.ATOMIC_MOVE);

}

From source file:org.apache.flink.tests.util.FlinkDistribution.java

@Override
public void afterTestSuccess() {
    try {//from w w w .  ja v a2 s.  c  om
        stopFlinkCluster();
    } catch (IOException e) {
        LOG.error("Failure while shutting down Flink cluster.", e);
    }

    final Path originalConfig = conf.resolve(FLINK_CONF_YAML);
    final Path backupConfig = conf.resolve(FLINK_CONF_YAML_BACKUP);

    try {
        Files.move(backupConfig, originalConfig, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        LOG.error("Failed to restore flink-conf.yaml", e);
    }

    for (AutoCloseable fileToDelete : filesToDelete) {
        try {
            fileToDelete.close();
        } catch (Exception e) {
            LOG.error("Failure while cleaning up file.", e);
        }
    }
}

From source file:com.github.zhanhb.ckfinder.connector.utils.ImageUtils.java

/**
 * Uploads image and if the image size is larger than maximum allowed it
 * resizes the image.//from   ww  w  . ja v  a  2s. c  om
 *
 * @param part servlet part
 * @param file file name
 * @param fileName name of file
 * @param context ckfinder context
 * @throws IOException when IO Exception occurs.
 */
public static void createTmpThumb(InputStreamSource part, Path file, String fileName, CKFinderContext context)
        throws IOException {
    BufferedImage image;
    try (InputStream stream = part.getInputStream()) {
        image = ImageIO.read(stream);
        if (image == null) {
            throw new IOException("Wrong file");
        }
    }
    ImageProperties imageProperties = context.getImage();
    Dimension dimension = createThumbDimension(image, imageProperties.getMaxWidth(),
            imageProperties.getMaxHeight());
    if (dimension.width == 0 || dimension.height == 0
            || (image.getHeight() <= dimension.height && image.getWidth() <= dimension.width)) {
        try (InputStream stream = part.getInputStream()) {
            Files.copy(stream, file, StandardCopyOption.REPLACE_EXISTING);
        }
    } else {
        resizeImage(image, dimension.width, dimension.height, imageProperties.getQuality(), file);
    }
    if (log.isTraceEnabled()) {
        log.trace("thumb size: {}", Files.size(file));
    }
}