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.ballerinalang.stdlib.system.FileSystemTest.java

@Test(description = "Test for removing file/directory from system")
public void testFileRemove() throws IOException {
    Path tempSourceDirPath = null;
    try {/*from www.  j a v a 2  s  . c o m*/
        tempSourceDirPath = tempDirPath.resolve("src-dir");
        FileUtils.copyDirectory(srcDirPath.toFile(), tempSourceDirPath.toFile());
        Files.copy(srcFilePath, tempSourcePath, StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES);
        // Remove source file
        BValue[] args = { new BString(tempSourcePath.toString()), new BBoolean(false) };
        BRunUtil.invoke(compileResult, "testRemove", args);
        assertFalse(Files.exists(tempSourcePath));

        // Remove directory with recursive false
        BValue[] args1 = { new BString(tempSourceDirPath.toString()), new BBoolean(false) };
        BValue[] returns = BRunUtil.invoke(compileResult, "testRemove", args1);
        assertTrue(returns[0] instanceof BError);
        BError error = (BError) returns[0];
        assertEquals(error.getReason(), "{ballerina/system}OPERATION_FAILED");
        log.info("Ballerina error: " + error.getDetails().stringValue());

        // Remove directory with recursive true
        BValue[] args2 = { new BString(tempSourceDirPath.toString()), new BBoolean(true) };
        returns = BRunUtil.invoke(compileResult, "testRemove", args2);
        assertNull(returns[0]);
        assertFalse(Files.exists(tempSourceDirPath));

    } finally {
        Files.deleteIfExists(tempSourcePath);
        if (tempSourceDirPath != null) {
            FileUtils.deleteDirectory(tempSourceDirPath.toFile());
        }
    }
}

From source file:org.ng200.openolympus.cerberus.executors.SandboxedExecutor.java

@Override
public void getFile(final String name, final Path destination) throws IOException {
    FileAccess.copy(this.storage.getPath().resolve("chroot").resolve(name), destination,
            StandardCopyOption.REPLACE_EXISTING);
}

From source file:org.apache.tika.eval.TikaEvalCLI.java

private void handleProfile(String[] subsetArgs) throws Exception {
    List<String> argList = new ArrayList(Arrays.asList(subsetArgs));

    boolean containsBC = false;
    String inputDir = null;//from   ww  w. j a  v  a2 s.  co m
    String extracts = null;
    String alterExtract = null;
    //confirm there's a batch-config file
    for (int i = 0; i < argList.size(); i++) {
        String arg = argList.get(i);
        if (arg.equals("-bc")) {
            containsBC = true;
        } else if (arg.equals("-inputDir")) {
            if (i + 1 >= argList.size()) {
                System.err.println("Must specify directory after -inputDir");
                ExtractProfiler.USAGE();
                return;
            }
            inputDir = argList.get(i + 1);
            i++;
        } else if (arg.equals("-extracts")) {
            if (i + 1 >= argList.size()) {
                System.err.println("Must specify directory after -extracts");
                ExtractProfiler.USAGE();
                return;
            }
            extracts = argList.get(i + 1);
            i++;
        } else if (arg.equals("-alterExtract")) {
            if (i + 1 >= argList.size()) {
                System.err.println("Must specify type 'as_is', 'first_only' or "
                        + "'concatenate_content' after -alterExtract");
                ExtractComparer.USAGE();
                return;
            }
            alterExtract = argList.get(i + 1);
            i++;
        }
    }

    if (alterExtract != null && !alterExtract.equals("as_is") && !alterExtract.equals("concatenate_content")
            && !alterExtract.equals("first_only")) {
        System.out.println("Sorry, I don't understand:" + alterExtract
                + ". The values must be one of: as_is, first_only, concatenate_content");
        ExtractProfiler.USAGE();
        return;
    }

    //need to specify each in this commandline
    //if only extracts is passed to tika-batch,
    //the crawler will see no inputDir and start crawling "input".
    //this allows the user to specify either extracts or inputDir
    if (extracts == null && inputDir != null) {
        argList.add("-extracts");
        argList.add(inputDir);
    } else if (inputDir == null && extracts != null) {
        argList.add("-inputDir");
        argList.add(extracts);
    }

    Path tmpBCConfig = null;
    try {
        tmpBCConfig = Files.createTempFile("tika-eval-profiler", ".xml");
        if (!containsBC) {
            Files.copy(this.getClass().getResourceAsStream("/tika-eval-profiler-config.xml"), tmpBCConfig,
                    StandardCopyOption.REPLACE_EXISTING);
            argList.add("-bc");
            argList.add(tmpBCConfig.toAbsolutePath().toString());
        }

        String[] updatedArgs = argList.toArray(new String[argList.size()]);
        DefaultParser defaultCLIParser = new DefaultParser();
        try {
            CommandLine commandLine = defaultCLIParser.parse(ExtractProfiler.OPTIONS, updatedArgs);
            if (commandLine.hasOption("db") && commandLine.hasOption("jdbc")) {
                System.out.println("Please specify either the default -db or the full -jdbc, not both");
                ExtractProfiler.USAGE();
                return;
            }
        } catch (ParseException e) {
            System.out.println(e.getMessage() + "\n");
            ExtractProfiler.USAGE();
            return;
        }

        FSBatchProcessCLI.main(updatedArgs);
    } finally {
        if (tmpBCConfig != null && Files.isRegularFile(tmpBCConfig)) {
            Files.delete(tmpBCConfig);
        }
    }
}

From source file:org.apache.beam.sdk.io.LocalFileSystem.java

@Override
protected void copy(List<LocalResourceId> srcResourceIds, List<LocalResourceId> destResourceIds)
        throws IOException {
    checkArgument(srcResourceIds.size() == destResourceIds.size(),
            "Number of source files %s must equal number of destination files %s", srcResourceIds.size(),
            destResourceIds.size());//from  w  ww  . j  av a2  s .  c  o  m
    int numFiles = srcResourceIds.size();
    for (int i = 0; i < numFiles; i++) {
        LocalResourceId src = srcResourceIds.get(i);
        LocalResourceId dst = destResourceIds.get(i);
        LOG.debug("Copying {} to {}", src, dst);
        File parent = dst.getCurrentDirectory().getPath().toFile();
        if (!parent.exists()) {
            checkArgument(parent.mkdirs() || parent.exists(),
                    "Unable to make output directory %s in order to copy into file %s", parent, dst.getPath());
        }
        // Copy the source file, replacing the existing destination.
        // Paths.get(x) will not work on Windows OSes cause of the ":" after the drive letter.
        Files.copy(src.getPath(), dst.getPath(), StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES);
    }
}

From source file:org.osiam.OsiamHome.java

private void copyToHome(Resource resource, Path osiamHomeDir) throws IOException {
    String pathUnderHome = resource.getURL().toString().replaceFirst(".*home/", "");
    Path target = osiamHomeDir.resolve(pathUnderHome);
    Files.createDirectories(target.getParent());
    Files.copy(resource.getInputStream(), target, StandardCopyOption.REPLACE_EXISTING);
}

From source file:org.apache.solr.core.StandardDirectoryFactory.java

public void renameWithOverwrite(Directory dir, String fileName, String toName) throws IOException {
    Directory baseDir = getBaseDir(dir);
    if (baseDir instanceof FSDirectory) {
        Path path = ((FSDirectory) baseDir).getDirectory().toAbsolutePath();
        try {/*from  w w  w. j  a va2  s. c o  m*/
            Files.move(path.resolve(fileName), path.resolve(toName), StandardCopyOption.ATOMIC_MOVE,
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (AtomicMoveNotSupportedException e) {
            Files.move(FileSystems.getDefault().getPath(path.toString(), fileName),
                    FileSystems.getDefault().getPath(path.toString(), toName),
                    StandardCopyOption.REPLACE_EXISTING);
        }
    } else {
        super.renameWithOverwrite(dir, fileName, toName);
    }
}

From source file:de.ncoder.studipsync.studip.jsoup.JsoupStudipAdapter.java

public void displayWebsite() {
    try {// w  ww .j  ava 2  s  .  com
        Path tmp = Files.createTempFile("studip-dump", ".html");
        Files.copy(new ByteArrayInputStream(document.outerHtml().getBytes()), tmp,
                StandardCopyOption.REPLACE_EXISTING);
        log.info("Displaying " + con.url());
        ui.displayWebpage(tmp.toUri());
    } catch (IOException e) {
        log.warn("Can't write page dump", e);
    }
}

From source file:com.skynetcomputing.skynetclient.persistence.PersistenceManager.java

/**
 * Saves given data file to file system, and returns the SrzData object.
 *
 * @param dataFile/*from w  w  w.ja  va 2 s  . co  m*/
 * @return
 * @throws IOException
 */
public SrzData saveDataFile(File dataFile) throws IOException {
    File dataDir = new File(rootDir + TASK_DIR + DATA_DIR);
    dataDir.mkdirs();
    SrzData output = readDataFile(dataFile);
    File outputFile = new File(
            String.format("%s%s%s%d%s", rootDir, TASK_DIR, DATA_DIR, output.getID(), SrzData.EXT));
    Files.copy(dataFile.toPath(), outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    return output;
}

From source file:joachimeichborn.geotag.io.jpeg.PictureMetadataWriter.java

private void replaceOriginalWithAnnotated(final Path originalFile, final Path annotatedFile)
        throws IOException {
    Files.move(annotatedFile, originalFile, StandardCopyOption.REPLACE_EXISTING);
}

From source file:com.tocsi.images.ImageListBean.java

public void handleFileUpload(FileUploadEvent event) {
    if (event.getFile() != null) {
        try {//from  ww w .j  a v a2s . c o  m
            UploadedFile uf = (UploadedFile) event.getFile();
            File folder = new File(GlobalsBean.destOriginal);
            //File folderThumb = new File(destThumbnail);
            String filename = FilenameUtils.getBaseName(uf.getFileName());
            String extension = FilenameUtils.getExtension(uf.getFileName());
            File file = File.createTempFile(filename + "-", "." + extension, folder);
            //File fileThumb = File.createTempFile(filename + "-", "." + extension, folderThumb);

            //resize image here
            BufferedImage originalImage = ImageIO.read(uf.getInputstream());
            InputStream is = uf.getInputstream();
            if (originalImage.getWidth() > 700) { //resize image if image's width excess 700px
                BufferedImage origImage = Scalr.resize(originalImage, Scalr.Method.QUALITY,
                        Scalr.Mode.FIT_TO_WIDTH, 640,
                        (int) ((originalImage.getHeight() / ((double) (originalImage.getWidth() / 700.0)))),
                        Scalr.OP_ANTIALIAS);
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(origImage, extension, os);
                is = new ByteArrayInputStream(os.toByteArray());
            }

            //create thumbnail
            BufferedImage thumbnail = Scalr.resize(ImageIO.read(uf.getInputstream()), 150);
            ByteArrayOutputStream osThumb = new ByteArrayOutputStream();
            ImageIO.write(thumbnail, extension, osThumb);
            InputStream isThumbnail = new ByteArrayInputStream(osThumb.toByteArray());

            try (InputStream input = is) {
                Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }

            try (InputStream input = isThumbnail) {
                Files.copy(input, Paths.get(GlobalsBean.destThumbnail + GlobalsBean.separator + file.getName()),
                        StandardCopyOption.REPLACE_EXISTING);
            }

            //File chartFile = new File(file.getAbsolutePath());
            //chart = new DefaultStreamedContent(new FileInputStream(chartFile), "image/jpg");
            ImageBean ib = new ImageBean();
            ib.setFilename(file.getName());
            ib.setThumbFile(file.getName());
            ib.setImageFileLocation(GlobalsBean.destOriginal + GlobalsBean.separator + file.getName());
            imageList.add(ib);
        } catch (IOException | IllegalArgumentException | ImagingOpException ex) {
            Utilities.displayError(ex.getMessage());
        }
    }
}