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.structr.media.FrameGrabberProcess.java

@Override
public Image processExited(int exitCode) {

    final App app = StructrApp.getInstance(securityContext);

    if (exitCode == 0) {

        try (final Tx tx = app.tx()) {

            // move converted file into place
            final java.io.File diskFile = new java.io.File(outputFileName + fileExtension);
            final java.io.File dstFile = new java.io.File(outputFileName);
            if (diskFile.exists()) {

                Files.move(diskFile.toPath(), dstFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                FileHelper.updateMetadata(newFile);

                // create link between the two videos
                inputFile.setProperty(StructrApp.key(VideoFile.class, "posterImage"), newFile);
            }//from  w w  w .j  a  va2 s .c  o m

            tx.success();

        } catch (FrameworkException | IOException fex) {
            logger.warn("", fex);
        }

    } else {

        // delete file, conversion has failed
        try (final Tx tx = app.tx()) {

            app.delete(newFile);
            tx.success();

        } catch (FrameworkException fex) {
            logger.warn("", fex);
        }

    }

    return newFile;
}

From source file:misc.FileHandler.java

/**
 * Copies the source file with the given options to the target file. The
 * source is first copied to the system's default temporary directory and
 * the temporary copy is then moved to the target file. In order to avoid
 * performance problems, the file is directly copied from the source to a
 * temporary file in the target directory first, if the temporary directory
 * and the target file lie on a different <code>FileStore</code>. The
 * temporary file is also moved to the target file.
 * /*  ww  w .  j  a  v  a2s .  co  m*/
 * @param source
 *            the file to copy.
 * @param target
 *            the target location where the file should be stored. Must not
 *            be identical with source. The file might or might not exist.
 *            The parent directory must exist.
 * @param replaceExisting
 *            <code>true</code>, if the target file may be overwritten.
 *            Otherwise, <code>false</code>.
 * @return <code>true</code>, if the file was successfully copied.
 *         Otherwise, <code>false</code>.
 */
public static boolean copyFile(Path source, Path target, boolean replaceExisting) {
    if ((source == null) || !Files.isReadable(source)) {
        throw new IllegalArgumentException("source must exist and be readable!");
    }
    if (target == null) {
        throw new IllegalArgumentException("target may not be null!");
    }
    if (source.toAbsolutePath().normalize().equals(target.toAbsolutePath().normalize())) {
        throw new IllegalArgumentException("source and target must not match!");
    }

    boolean success = false;
    Path tempFile = null;

    target = target.normalize();

    try {
        tempFile = FileHandler.getTempFile(target);

        if (tempFile != null) {
            Files.copy(source, tempFile, StandardCopyOption.COPY_ATTRIBUTES,
                    StandardCopyOption.REPLACE_EXISTING);
            if (replaceExisting) {
                Files.move(tempFile, target, StandardCopyOption.REPLACE_EXISTING);
            } else {
                Files.move(tempFile, target);
            }
            success = true;
        }
    } catch (IOException e) {
        Logger.logError(e);
    } finally {
        if (tempFile != null) {
            try {
                Files.deleteIfExists(tempFile);
            } catch (IOException eDelete) {
                Logger.logError(eDelete);
            }
        }
    }

    return success;
}

From source file:com.kantenkugel.discordbot.moduleutils.DocParser.java

private static void download() {
    LOG.info("Downloading source-file");
    try {//w ww  .ja  v a2 s .c o m
        HttpResponse<String> response = Unirest.get(JENKINS_PREFIX + ARTIFACT_SUFFIX).asString();
        if (response.getStatus() < 300 && response.getStatus() > 199) {
            JSONArray artifacts = new JSONObject(response.getBody()).getJSONArray("artifacts");
            for (int i = 0; i < artifacts.length(); i++) {
                JSONObject artifact = artifacts.getJSONObject(i);
                if (artifact.getString("fileName").endsWith("sources.jar")) {
                    URL artifactUrl = new URL(
                            JENKINS_PREFIX + "artifact/" + artifact.getString("relativePath"));
                    InputStream is = artifactUrl.openStream();
                    Files.copy(is, LOCAL_SRC_PATH, StandardCopyOption.REPLACE_EXISTING);
                    is.close();
                    LOG.info("Done downloading source-file");
                }
            }
        }
    } catch (UnirestException | IOException e) {
        LOG.log(e);
    }
}

From source file:com.seleniumtests.driver.DriverExtractor.java

public void copyDriver(String driverName) {
    InputStream driver = Thread.currentThread().getContextClassLoader().getResourceAsStream(String
            .format("drivers/%s/%s%s", os, driverName, OSUtilityFactory.getInstance().getProgramExtension()));

    if (driver == null) {
        throw new DriverExceptions(String.format("Driver %s does not exist in resources", driverName));
    }//from  w w  w.j  a  v  a2  s  . c  om
    Path driverPath = getDriverPath(driverName);

    driverPath.toFile().getParentFile().mkdirs();

    try {
        Files.copy(driver, driverPath, StandardCopyOption.REPLACE_EXISTING);
        driverPath.toFile().setExecutable(true);
        logger.info(String.format("Driver %s copied to %s", driverName, driverPath));
    } catch (IOException e) {
        logger.info(String.format("Driver not copied: %s - it may be in use", driverName));
    }

}

From source file:ru.histone.staticrender.StaticRender.java

public void renderSite(final Path srcDir, final Path dstDir) {
    log.info("Running StaticRender for srcDir={}, dstDir={}", srcDir.toString(), dstDir.toString());
    Path contentDir = srcDir.resolve("content/");
    final Path layoutDir = srcDir.resolve("layouts/");

    FileVisitor<Path> layoutVisitor = new SimpleFileVisitor<Path>() {
        @Override/* w w w  .  ja v a 2s. c o m*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (file.toString().endsWith("." + TEMPLATE_FILE_EXTENSION)) {
                ArrayNode ast = null;
                try {
                    ast = histone.parseTemplateToAST(new FileReader(file.toFile()));
                } catch (HistoneException e) {
                    throw new RuntimeException("Error parsing histone template:" + e.getMessage(), e);
                }

                final String fileName = file.getFileName().toString();
                String layoutId = fileName.substring(0,
                        fileName.length() - TEMPLATE_FILE_EXTENSION.length() - 1);
                layouts.put(layoutId, ast);
                if (log.isDebugEnabled()) {
                    log.debug("Layout found id='{}', file={}", layoutId, file);
                } else {
                    log.info("Layout found id='{}'", layoutId);
                }
            } else {
                final Path relativeFileName = srcDir.resolve("layouts").relativize(Paths.get(file.toUri()));
                final Path resolvedFile = dstDir.resolve(relativeFileName);
                if (!resolvedFile.getParent().toFile().exists()) {
                    Files.createDirectories(resolvedFile.getParent());
                }
                Files.copy(Paths.get(file.toUri()), resolvedFile, StandardCopyOption.REPLACE_EXISTING,
                        LinkOption.NOFOLLOW_LINKS);
            }
            return FileVisitResult.CONTINUE;
        }
    };

    FileVisitor<Path> contentVisitor = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

            Scanner scanner = new Scanner(file, "UTF-8");
            scanner.useDelimiter("-----");

            String meta = null;
            StringBuilder content = new StringBuilder();

            if (!scanner.hasNext()) {
                throw new RuntimeException("Wrong format #1:" + file.toString());
            }

            if (scanner.hasNext()) {
                meta = scanner.next();
            }

            if (scanner.hasNext()) {
                content.append(scanner.next());
                scanner.useDelimiter("\n");
            }

            while (scanner.hasNext()) {
                final String next = scanner.next();
                content.append(next);

                if (scanner.hasNext()) {
                    content.append("\n");
                }
            }

            Map<String, String> metaYaml = (Map<String, String>) yaml.load(meta);

            String layoutId = metaYaml.get("layout");

            if (!layouts.containsKey(layoutId)) {
                throw new RuntimeException(MessageFormat.format("No layout with id='{0}' found", layoutId));
            }

            final Path relativeFileName = srcDir.resolve("content").relativize(Paths.get(file.toUri()));
            final Path resolvedFile = dstDir.resolve(relativeFileName);
            if (!resolvedFile.getParent().toFile().exists()) {
                Files.createDirectories(resolvedFile.getParent());
            }
            Writer output = new FileWriter(resolvedFile.toFile());
            ObjectNode context = jackson.createObjectNode();
            ObjectNode metaNode = jackson.createObjectNode();
            context.put("content", content.toString());
            context.put("meta", metaNode);
            for (String key : metaYaml.keySet()) {
                if (!key.equalsIgnoreCase("content")) {
                    metaNode.put(key, metaYaml.get(key));
                }
            }

            try {
                histone.evaluateAST(layoutDir.toUri().toString(), layouts.get(layoutId), context, output);
                output.flush();
            } catch (HistoneException e) {
                throw new RuntimeException("Error evaluating content: " + e.getMessage(), e);
            } finally {
                output.close();
            }

            return FileVisitResult.CONTINUE;
        }
    };

    try {
        Files.walkFileTree(layoutDir, layoutVisitor);
        Files.walkFileTree(contentDir, contentVisitor);
    } catch (Exception e) {
        throw new RuntimeException("Error during site render", e);
    }
}

From source file:com.ibm.liberty.starter.api.v1.LibertyFileUploader.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String tech = request.getParameter(PARAMETER_TECH);
    String workspaceId = request.getParameter(PARAMETER_WORKSPACE); //specify the unique workspace directory to upload the file(s) to.   
    Collection<Part> filePartCollection = request.getParts();

    String serverHostPort = request.getRequestURL().toString().replace(request.getRequestURI(), "");
    int schemeLength = request.getScheme().toString().length();
    String internalHostPort = "http" + serverHostPort.substring(schemeLength);
    log.log(Level.FINER, "serverHostPort : " + serverHostPort);
    final ServiceConnector serviceConnector = new ServiceConnector(serverHostPort, internalHostPort);
    HashMap<Part, String> fileNames = new HashMap<Part, String>();
    if (!isValidRequest(request, response, tech, workspaceId, filePartCollection, serviceConnector,
            fileNames)) {/*from   ww w  .j av a2 s . co m*/
        return;
    }

    Service techService = serviceConnector.getServiceObjectFromId(tech);
    String techDirPath = StarterUtil.getWorkspaceDir(workspaceId) + "/" + techService.getId();
    File techDir = new File(techDirPath);
    if (techDir.exists() && techDir.isDirectory()
            && "true".equalsIgnoreCase(request.getParameter(PARAMETER_CLEANUP))) {
        FileUtils.cleanDirectory(techDir);
        log.log(Level.FINER, "Cleaned up tech workspace directory : " + techDirPath);
    }

    for (Part filePart : filePartCollection) {
        if (!techDir.exists()) {
            FileUtils.forceMkdir(techDir);
            log.log(Level.FINER, "Created tech directory :" + techDirPath);
        }

        String filePath = techDirPath + "/" + fileNames.get(filePart);
        log.log(Level.FINER, "File path : " + filePath);
        File uploadedFile = new File(filePath);

        Files.copy(filePart.getInputStream(), uploadedFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        log.log(Level.FINE, "Copied file to " + filePath);
    }

    if ("true".equalsIgnoreCase(request.getParameter(PARAMETER_PROCESS))) {
        // Process uploaded file(s)
        String processResult = serviceConnector.processUploadedFiles(techService, techDirPath);
        if (!processResult.equalsIgnoreCase("success")) {
            log.log(Level.INFO,
                    "Error processing the files uploaded to " + techDirPath + " : Result=" + processResult);
            response.sendError(500, processResult);
            return;
        }
        log.log(Level.FINE, "Processed the files uploaded to " + techDirPath);
    }

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("success");
    out.close();
}

From source file:org.wisdom.maven.osgi.BundlePackager.java

/**
 * Creates the bundle.//from ww w .j a va  2  s. c o m
 *
 * @param basedir the project's base directory
 * @param output  the output file
 * @throws IOException occurs when the bundle cannot be built correctly.
 */
public static void bundle(File basedir, File output, Reporter reporter) throws IOException {
    ProjectScanner scanner = new ProjectScanner(basedir);

    // Loads the properties inherited from Maven.
    Properties instructions = readMavenProperties(basedir);
    // Loads the properties from the BND file.
    Properties fromBnd = readInstructionsFromBndFile(basedir);
    if (fromBnd == null) {
        // No bnd files, use default instructions
        instructions = populatePropertiesWithDefaults(basedir, instructions, scanner);
    } else {
        // We have a BND file.
        // Do we have to merge ?
        String noDefaultValue = fromBnd.getProperty("-no-default");
        if (!"true".equalsIgnoreCase(noDefaultValue)) {
            // So we need to merge the default with the bnd files
            // 1) merge the instructions from the bnd files with the default
            // 2) merge the resulting set of instruction onto the maven properties
            // (and override the default)
            instructions = Instructions.mergeAndOverrideExisting(instructions,
                    populatePropertiesWithDefaults(basedir, fromBnd, scanner));
        } else {
            instructions = Instructions.mergeAndOverrideExisting(instructions, fromBnd);
        }
    }

    // Manage Embedded dependencies
    DependencyEmbedder ed = new DependencyEmbedder(instructions, reporter);
    instructions = ed.generate(instructions, org.wisdom.maven.osgi.Classpath.load(basedir));

    // Integrate custom headers added by other plugins.
    instructions = mergeExtraHeaders(basedir, instructions);

    // For debugging purpose, dump the instructions to target/osgi/instructions.properties
    FileOutputStream fos = null;
    try {
        File out = new File(basedir, "target/osgi/instructions.properties");
        fos = new FileOutputStream(out);
        instructions.store(fos, "Wisdom BND Instructions");
    } catch (IOException e) { // NOSONAR
        // Ignore it.
    } finally {
        IOUtils.closeQuietly(fos);
    }

    // Instructions loaded, start the build sequence.
    final Jar[] jars = org.wisdom.maven.osgi.Classpath.computeClassPath(basedir);

    File bnd;
    File ipojo;
    Builder builder = null;
    try {
        builder = getOSGiBuilder(basedir, instructions, jars);
        // The next sequence is weird
        // First build the bundle with the given instruction
        // Then analyze to apply the plugin and fix
        // finally, rebuild with the updated metadata
        // Without the first build, embedded dependencies and private packages from classpath are not analyzed.
        builder.build();
        builder.analyze();
        builder.build();

        reportErrors(builder.getWarnings(), builder.getErrors(), reporter);
        bnd = File.createTempFile("bnd-", ".jar");
        ipojo = File.createTempFile("ipojo-", ".jar");
        builder.getJar().write(bnd);
    } catch (Exception e) {
        throw new IOException("Cannot build the OSGi bundle", e);
    } finally {
        if (builder != null) {
            builder.close();
        }
    }

    final Set<String> elements = org.wisdom.maven.osgi.Classpath.computeClassPathElement(basedir);
    Classpath classpath = new Classpath(elements);
    Pojoization pojoization = new Pojoization();
    pojoization.pojoization(bnd, ipojo, new File(basedir, "src/main/resources"), classpath.createClassLoader());
    reportErrors(pojoization.getWarnings(), pojoization.getErrors(), reporter);

    Files.move(Paths.get(ipojo.getPath()), Paths.get(output.getPath()), StandardCopyOption.REPLACE_EXISTING);
}

From source file:dotaSoundEditor.Controls.EditorPanel.java

protected File promptUserForNewFile(String wavePath) {
    JFileChooser chooser = new JFileChooser(new File(UserPrefs.getInstance().getWorkingDirectory()));
    FileNameExtensionFilter filter = new FileNameExtensionFilter("MP3s and WAVs", "mp3", "wav");
    chooser.setAcceptAllFileFilterUsed((false));
    chooser.setFileFilter(filter);// w w w  . j  a  v  a 2 s  .  c  o  m
    chooser.setMultiSelectionEnabled(false);

    int chooserRetVal = chooser.showOpenDialog(chooser);
    if (chooserRetVal == JFileChooser.APPROVE_OPTION) {
        DefaultMutableTreeNode selectedFile = (DefaultMutableTreeNode) getTreeNodeFromWavePath(wavePath);
        Path chosenFile = Paths.get(chooser.getSelectedFile().getAbsolutePath());
        //Strip caps and spaces out of filenames. The item sound parser seems to have trouble with them.
        String destFileName = chosenFile.getFileName().toString().toLowerCase().replace(" ", "_");
        Path destPath = Paths.get(installDir, "/dota/sound/" + getCustomSoundPathString() + destFileName);
        UserPrefs.getInstance().setWorkingDirectory(chosenFile.getParent().toString());

        try {
            new File(destPath.toString()).mkdirs();
            Files.copy(chosenFile, destPath, StandardCopyOption.REPLACE_EXISTING);

            String waveString = selectedFile.getUserObject().toString();
            int startIndex = -1;
            int endIndex = -1;
            if (waveString.contains("\"wave\"")) {
                startIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 2);
                endIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 3);
            } else //Some wavestrings don't have the "wave" at the beginning for some reason
            {
                startIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 0);
                endIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 1);
            }

            String waveStringFilePath = waveString.substring(startIndex, endIndex + 1);
            waveString = waveString.replace(waveStringFilePath,
                    "\"" + getCustomSoundPathString() + destFileName + "\"");
            selectedFile.setUserObject(waveString);

            //Write out modified tree to scriptfile.
            ScriptParser parser = new ScriptParser(this.currentTreeModel);
            String scriptString = getCurrentScriptString();
            Path scriptPath = Paths.get(scriptString);
            parser.writeModelToFile(scriptPath.toString());

            //Update UI
            ((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent()).setUserObject(waveString);
            ((DefaultTreeModel) currentTree.getModel())
                    .nodeChanged((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent());
            JOptionPane.showMessageDialog(this, "Sound file successfully replaced.");

        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Unable to replace sound.\nDetails: " + ex.getMessage(),
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    return null;
}

From source file:com.frostwire.gui.library.DownloadTask.java

@Override
public void run() {
    if (!isRunning()) {
        return;/* w ww. jav  a  2s . c  om*/
    }

    File lastFile = null;

    try {
        setProgress(0);

        if (!savePath.exists()) {
            savePath.mkdirs();
        }

        long totalBytes = getTotalBytes();
        long totalWritten = 0;

        for (int i = 0; i < fds.length; i++) {
            if (!isRunning()) {
                return;
            }

            currentFD = fds[i];

            GUIMediator.safeInvokeLater(new Runnable() {
                public void run() {
                    String status = String.format("%s from %s - %s", I18n.tr("Downloading"), device.getName(),
                            currentFD.title);
                    LibraryMediator.instance().getLibrarySearch().pushStatus(status);
                }
            });

            URL url = new URL(device.getDownloadURL(currentFD));

            InputStream is = null;
            OutputStream fos = null;

            try {
                is = url.openStream();

                String filename = OSUtils.escapeFilename(FilenameUtils.getName(currentFD.filePath));
                File file = buildFile(savePath, filename);
                Path incompleteFile = buildIncompleteFile(file).toPath();
                lastFile = file.getAbsoluteFile();

                fos = Files.newOutputStream(incompleteFile, StandardOpenOption.CREATE);// new FileOutputStream(incompleteFile);

                byte[] buffer = new byte[4 * 1024];
                int n = 0;

                while ((n = is.read(buffer, 0, buffer.length)) != -1) {
                    if (!isRunning()) {
                        return;
                    }

                    fos.write(buffer, 0, n);
                    fos.flush();
                    totalWritten += n;
                    setProgress((int) ((totalWritten * 100) / totalBytes));

                    if (getProgress() % 5 == 0) {
                        GUIMediator.safeInvokeLater(new Runnable() {
                            public void run() {
                                String status = String.format("%d%% %s from %s - %s", getProgress(),
                                        I18n.tr("Downloading"), device.getName(), currentFD.title);
                                LibraryMediator.instance().getLibrarySearch().pushStatus(status);
                            }
                        });
                    }

                    //System.out.println("Progress: " + getProgress() + " Total Written: " + totalWritten + " Total Bytes: " + totalBytes);
                }

                close(fos);
                Files.move(incompleteFile, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
            } finally {
                close(is);
                close(fos);
            }
        }

        setProgress(100);
    } catch (Throwable e) {
        e.printStackTrace();
        onError(e);

        GUIMediator.safeInvokeLater(new Runnable() {
            public void run() {
                LibraryMediator.instance().getLibrarySearch()
                        .pushStatus(I18n.tr("Wi-Fi download error. Please try again."));
            }
        });
    } finally {
        GUIMediator.safeInvokeLater(new Runnable() {
            public void run() {
                LibraryMediator.instance().getLibrarySearch().revertStatus();
            }
        });

        if (lastFile != null) {
            GUIMediator.launchExplorer(lastFile);
        }
    }

    stop();
}