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.apdplat.superword.tools.PdfParser.java

public static void parseZip(String zipFile) {
    long start = System.currentTimeMillis();
    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  v  a 2 s .co  m
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    LOGGER.info("?" + file);
                    // ?
                    Path temp = Paths.get("target/it-software-domain-temp.pdf");
                    Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING);
                    parseFile(temp.toFile().getAbsolutePath());
                    return FileVisitResult.CONTINUE;
                }

            });
        }
    } catch (Exception e) {
        LOGGER.error("?", e);
    }
    long cost = System.currentTimeMillis() - start;
    LOGGER.info("?" + cost + "");
}

From source file:net.daboross.bukkitdev.skywars.score.JSONScoreStorage.java

@Override
public void save() throws IOException {
    if (!Files.exists(saveFileBuffer)) {
        Files.createFile(saveFileBuffer);
    }/*from ww w  .  j  av a  2s  . c o m*/
    try (FileOutputStream fos = new FileOutputStream(saveFileBuffer.toFile())) {
        try (OutputStreamWriter writer = new OutputStreamWriter(fos, Charset.forName("UTF-8"))) {
            baseJson.write(writer);
        }
    } catch (IOException | JSONException ex) {
        throw new IOException("Couldn't write to " + saveFileBuffer.toAbsolutePath(), ex);
    }
    try {
        Files.move(saveFileBuffer, saveFile, StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.ATOMIC_MOVE);
    } catch (IOException ex) {
        throw new IOException("Failed to move buffer file '" + saveFileBuffer.toAbsolutePath()
                + "' to actual save location '" + saveFile + "'", ex);
    }
}

From source file:org.apdplat.superword.tools.WordClassifierForYouDao.java

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

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

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

From source file:org.kaaproject.kaa.avro.avrogen.compiler.Compiler.java

/**
 * Instantiates a new Compiler./*from ww  w  .j  a v  a2 s.co m*/
 *
 * @param schemaPath path to file that contains schema
 * @param outputPath destination path for generated sources
 * @param sourceName name of source files
 */
public Compiler(String schemaPath, String outputPath, String sourceName) throws KaaGeneratorException {
    this(sourceName);
    try {
        this.schemas.add(new Schema.Parser().parse(new File(schemaPath)));

        prepareTemplates(true);

        File outputDir = new File(outputPath);
        outputDir.mkdirs();

        String headerPath = outputPath + File.separator + generatedSourceName + ".h";
        String sourcePath = outputPath + File.separator + generatedSourceName + getSourceExtension();

        Files.move(new File(headerTemplateGen()).toPath(), new File(headerPath).toPath(),
                StandardCopyOption.REPLACE_EXISTING);
        Files.move(new File(sourceTemplateGen()).toPath(), new File(sourcePath).toPath(),
                StandardCopyOption.REPLACE_EXISTING);

        this.headerWriter = new PrintWriter(new BufferedWriter(new FileWriter(headerPath, true)));
        this.sourceWriter = new PrintWriter(new BufferedWriter(new FileWriter(sourcePath, true)));
    } catch (Exception ex) {
        LOG.error("Failed to create ouput path: ", ex);
        throw new KaaGeneratorException("Failed to create output path: " + ex.toString());
    }
}

From source file:de.unirostock.sems.caroweb.Converter.java

private void run(HttpServletRequest request, HttpServletResponse response, String uploadedName, String[] req,
        File tmp, File out, Path STORAGE) throws ServletException, IOException {
    cleanUp();/*  ww w  . jav  a  2  s . co  m*/

    uploadedName.replaceAll("[^A-Za-z0-9 ]", "_");
    if (uploadedName.length() < 3)
        uploadedName += "container";

    CaRoConverter conv = null;

    if (req[1].equals("caro"))
        conv = new CaToRo(tmp);
    else if (req[1].equals("roca"))
        conv = new RoToCa(tmp);
    else {
        error(request, response, "do not know what to do");
        return;
    }
    conv.convertTo(out);

    List<CaRoNotification> notifications = conv.getNotifications();

    Path result = null;
    if (out.exists()) {
        result = Files.createTempFile(STORAGE, uploadedName,
                "-converted-" + CaRoWebutils.getTimeStamp() + "." + (req[1].equals("caro") ? "ro" : "omex"));
        try {
            Files.copy(out.toPath(), result, StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            notifications.add(new CaRoNotification(CaRoNotification.SERVERITY_ERROR,
                    "wasn't able to copy converted container to storage"));
        }
    }

    JSONArray errors = new JSONArray();
    JSONArray warnings = new JSONArray();
    JSONArray notes = new JSONArray();
    for (CaRoNotification note : notifications)
        if (note.getSeverity() == CaRoNotification.SERVERITY_ERROR)
            errors.add(note.getMessage());
        else if (note.getSeverity() == CaRoNotification.SERVERITY_WARN)
            warnings.add(note.getMessage());
        else if (note.getSeverity() == CaRoNotification.SERVERITY_NOTE)
            notes.add(note.getMessage());

    JSONObject json = new JSONObject();
    json.put("errors", errors);
    json.put("warnings", warnings);
    json.put("notifications", notes);

    if (result != null && Files.exists(result)) {
        json.put("checkout", result.getFileName().toString());
        if (request.getParameter("redirect") != null && request.getParameter("redirect").equals("checkout")) {
            response.sendRedirect("/checkout/" + result.getFileName().toString());
        }
    }

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    PrintWriter outWriter = response.getWriter();
    outWriter.print(json);
    out.delete();
}

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

/**
 * Moves a directory/file from one path to another
 * /*from   w  ww. ja v  a2s . 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
 * @throws NotFoundException
 * 
 */
public static void move(final Path sourcePath, final Path targetPath, boolean replaceExisting)
        throws AlreadyExistsException, GenericException, NotFoundException {

    // 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 (FileAlreadyExistsException e) {
        // do nothing
    } catch (IOException e) {
        throw new GenericException("Error while creating target directory parent folder", e);
    }

    CopyOption[] copyOptions = replaceExisting ? new CopyOption[] { StandardCopyOption.REPLACE_EXISTING }
            : new CopyOption[] {};

    if (FSUtils.isDirectory(sourcePath)) {
        try {
            Files.move(sourcePath, targetPath, copyOptions);
        } catch (DirectoryNotEmptyException e) {
            // 20160826 hsilva: this might happen in some filesystems (e.g. XFS)
            // because moving a directory implies also moving its entries. In Ext4
            // this doesn't happen.
            LOGGER.debug("Moving recursively, as a fallback & instead of a simple move, from {} to {}",
                    sourcePath, targetPath);
            moveRecursively(sourcePath, targetPath, replaceExisting);
        } catch (IOException e) {
            throw new GenericException("Error while moving directory from " + sourcePath + " to " + targetPath,
                    e);
        }
    } else {
        try {
            Files.move(sourcePath, targetPath, copyOptions);
        } catch (NoSuchFileException e) {
            throw new NotFoundException("Could not find resource to move", e);
        } catch (IOException e) {
            throw new GenericException("Error while copying one file into another", e);
        }
    }
}

From source file:org.apache.taverna.download.impl.DownloadManagerImpl.java

@Override
public void download(URI source, Path destination, String digestAlgorithm, URI digestSource)
        throws DownloadException {

    MessageDigest md = null;/*from w ww  .  ja  va 2  s  . c om*/
    if (digestAlgorithm != null) {
        try {
            md = MessageDigest.getInstance(digestAlgorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("Unsupported digestAlgorithm: " + digestAlgorithm, e);
        }
    }

    // download the file
    Path tempFile;
    try {
        tempFile = Files.createTempFile(destination.getParent(), "." + destination.getFileName(), ".tmp");
    } catch (IOException e1) {
        // perhaps a permission problem?
        throw new DownloadException("Can't create temporary file in folder " + destination.getParent(), e1);
    }
    logger.info(String.format("Downloading %1$s to %2$s", source, tempFile));
    downloadToFile(source, tempFile);

    if (digestSource != null) {
        // download the digest file
        String expectedDigest;
        expectedDigest = downloadHash(digestSource).trim().toLowerCase(Locale.ROOT);
        // check if the digest matches
        try {
            try (InputStream s = Files.newInputStream(tempFile)) {
                DigestUtils.updateDigest(md, s);
                String actualDigest = Hex.encodeHexString(md.digest());
                if (!actualDigest.equals(expectedDigest)) {
                    throw new DownloadException(
                            String.format("Error downloading file: checksum mismatch (%1$s != %2$s)",
                                    actualDigest, expectedDigest));
                }
            }
        } catch (IOException e) {
            throw new DownloadException(String.format("Error checking digest for %1$s", destination), e);
        }
    }
    // All fine, move to destination
    try {
        logger.info(String.format("Copying %1$s to %2$s", tempFile, destination));
        Files.move(tempFile, destination, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new DownloadException(String.format("Error downloading %1$s to %2$s.", source, destination), e);
    }

}

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

@Override
public ExecutionResult execute(final Path program) throws IOException {

    final Path chrootRoot = this.storage.getPath().resolve("chroot");

    final Path chrootedProgram = chrootRoot.resolve(program.getFileName().toString());

    FileAccess.createDirectories(chrootedProgram);
    FileAccess.copyDirectory(program, chrootedProgram, StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.COPY_ATTRIBUTES);

    final Path outOfMemoryFile = chrootRoot.resolve("outOfMemory");

    final Path policyFile = this.storage.getPath().resolve("olymp.policy");

    try (Stream<Path> paths = FileAccess.walkPaths(storage.getPath())) {
        paths.forEach(path -> {//from  ww w  .jav  a2  s . c  om
            try {
                Files.setPosixFilePermissions(path,
                        new HashSet<PosixFilePermission>(
                                Lists.from(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ,
                                        PosixFilePermission.OWNER_WRITE, PosixFilePermission.GROUP_EXECUTE,
                                        PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_WRITE,
                                        PosixFilePermission.OTHERS_EXECUTE, PosixFilePermission.OTHERS_READ)));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

    this.buildPolicy(chrootRoot, policyFile);

    final CommandLine commandLine = new CommandLine("sudo");
    commandLine.addArgument("olympus_watchdog");

    this.setUpOlrunnerLimits(commandLine);

    commandLine.addArgument("--security=0");
    commandLine.addArgument("--jail=/");

    commandLine.addArgument("--");

    commandLine.addArgument("/usr/bin/java");

    commandLine.addArgument("-classpath");
    commandLine.addArgument(chrootedProgram.toAbsolutePath().toString());
    commandLine.addArgument("-Djava.security.manager");
    commandLine.addArgument("-Djava.security.policy=" + policyFile.toAbsolutePath().toString());

    commandLine.addArgument("-Xmx" + this.getMemoryLimit());
    commandLine.addArgument("-Xms" + this.getMemoryLimit());

    commandLine.addArgument(MessageFormat.format("-XX:OnOutOfMemoryError=touch {0}; echo \"\" > {0}",
            outOfMemoryFile.toAbsolutePath().toString()), false);

    commandLine.addArgument("Main");

    final DefaultExecutor executor = new DefaultExecutor();

    executor.setWatchdog(new ExecuteWatchdog(20000)); // 20 seconds for the
    // sandbox to
    // complete
    executor.setWorkingDirectory(chrootRoot.toFile());

    executor.setStreamHandler(new PumpStreamHandler(this.outputStream, this.errorStream, this.inputStream));
    try {
        executor.execute(commandLine);
    } catch (final IOException e) {
        if (!e.getMessage().toLowerCase().equals("stream closed")) {
            throw e;
        }
    }
    final ExecutionResult readOlrunnerVerdict = this.readOlrunnerVerdict(chrootRoot.resolve("verdict.txt"));

    if (FileAccess.exists(outOfMemoryFile)) {
        readOlrunnerVerdict.setResultType(ExecutionResultType.MEMORY_LIMIT);
    }

    readOlrunnerVerdict.setMemoryPeak(this.getMemoryLimit());

    return readOlrunnerVerdict;
}

From source file:org.fao.geonet.utils.XmlRequest.java

protected final Path doExecuteLarge(HttpRequestBase httpMethod, Path outFile) throws IOException {

    try (ClientHttpResponse httpResponse = doExecute(httpMethod)) {
        Files.copy(httpResponse.getBody(), outFile, StandardCopyOption.REPLACE_EXISTING);
        return outFile;
    } finally {/*from  ww  w  . j a v  a  2s. c  om*/
        httpMethod.releaseConnection();

        sentData = getSentData(httpMethod);
        //--- we do not save received data because it can be very large
    }
}

From source file:edu.harvard.iq.dataverse.dataaccess.DataFileIO.java

public void copyPath(Path fileSystemPath) throws IOException {
    long newFileSize = -1;
    // if this is a local fileystem file, we'll use a 
    // quick Files.copy method: 
    if (isLocalFile()) {
        Path outputPath = null;/*from www. jav a 2  s  .c  o  m*/
        try {
            outputPath = getFileSystemPath();
        } catch (IOException ex) {
            outputPath = null;
        }
        if (outputPath != null) {
            Files.copy(fileSystemPath, outputPath, StandardCopyOption.REPLACE_EXISTING);
            newFileSize = outputPath.toFile().length();
        }

    } else {
        // otherwise we'll open a writable byte channel and 
        // copy the source file bytes using Channel.transferTo():

        WritableByteChannel writeChannel = null;
        FileChannel readChannel = null;
        String failureMsg = null;

        try {

            open(DataAccessOption.WRITE_ACCESS);
            writeChannel = getWriteChannel();
            readChannel = new FileInputStream(fileSystemPath.toFile()).getChannel();

            long bytesPerIteration = 16 * 1024; // 16K bytes
            long start = 0;
            while (start < readChannel.size()) {
                readChannel.transferTo(start, bytesPerIteration, writeChannel);
                start += bytesPerIteration;
            }
            newFileSize = readChannel.size();

        } catch (IOException ioex) {
            failureMsg = ioex.getMessage();
            if (failureMsg == null) {
                failureMsg = "Unknown exception occured.";
            }
        } finally {
            if (readChannel != null) {
                try {
                    readChannel.close();
                } catch (IOException e) {
                }
            }
            if (writeChannel != null) {
                try {
                    writeChannel.close();
                } catch (IOException e) {
                }
            }
        }

        if (failureMsg != null) {
            throw new IOException(failureMsg);
        }
    }

    // if it has worked successfully, we also need to reset the size
    // of the object. 
    setSize(newFileSize);
}