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:com.thinkbiganalytics.feedmgr.rest.controller.FeedRestController.java

@POST
@Path("/{feedId}/upload-file")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)/*from  w w w . ja  v  a2  s .  c  om*/
@ApiOperation("Uploads a file to be ingested by a feed.")
@ApiResponses({ @ApiResponse(code = 200, message = "The file is ready to be ingested."),
        @ApiResponse(code = 500, message = "The file could not be saved.", response = RestResponseStatus.class) })
public Response uploadFile(@PathParam("feedId") String feedId,
        @FormDataParam("file") InputStream fileInputStream,
        @FormDataParam("file") FormDataContentDisposition fileMetaData) throws Exception {

    FeedMetadata feed = getMetadataService().getFeedById(feedId, false);
    // Derive path and file
    List<NifiProperty> properties = feed.getProperties();
    String dropzone = null;
    String regexFileFilter = null;

    for (NifiProperty property : properties) {

        if (property.getProcessorType().equals("org.apache.nifi.processors.standard.GetFile")) {
            if (property.getKey().equals("File Filter")) {
                regexFileFilter = property.getValue();
            } else if (property.getKey().equals("Input Directory")) {
                dropzone = property.getValue();
            }
        }
    }
    if (StringUtils.isEmpty(regexFileFilter) || StringUtils.isEmpty(dropzone)) {
        throw new IOException("Unable to upload file with empty dropzone and file");
    }
    File tempTarget = File.createTempFile("kylo-upload", "");
    String fileName = "";
    try {
        Generex fileNameGenerator = new Generex(regexFileFilter);
        fileName = fileNameGenerator.random();

        // Cleanup oddball characters generated by generex
        fileName = fileName.replaceAll("[^A-Za-z0-9\\.\\_\\+\\%\\-\\|]+", "\\.");
        java.nio.file.Path dropZoneTarget = Paths.get(dropzone, fileName);
        File dropZoneFile = dropZoneTarget.toFile();
        if (dropZoneFile.exists()) {
            throw new IOException("File with the name [" + fileName + "] already exists in [" + dropzone + "]");
        }

        Files.copy(fileInputStream, tempTarget.toPath(), StandardCopyOption.REPLACE_EXISTING);
        Files.move(tempTarget.toPath(), dropZoneTarget);

        // Set read, write
        dropZoneFile.setReadable(true);
        dropZoneFile.setWritable(true);

    } catch (AccessDeniedException e) {
        String errTemplate = "Permission denied attempting to write file [%s] to [%s]. Check with system administrator to ensure this application has write permissions to folder";
        String err = String.format(errTemplate, fileName, dropzone);
        log.error(err);
        throw new InternalServerErrorException(err);

    } catch (Exception e) {
        String errTemplate = "Unexpected exception writing file [%s] to [%s].";
        String err = String.format(errTemplate, fileName, dropzone);
        log.error(err);
        throw new InternalServerErrorException(err);
    }
    return Response.ok("").build();
}

From source file:org.apache.marmotta.platform.core.services.config.ConfigurationServiceImpl.java

protected void saveSecure(final PropertiesConfiguration conf) throws ConfigurationException {
    final File file = conf.getFile();
    try {// w w  w . jav a 2  s  .com
        if (file == null) {
            throw new ConfigurationException("No file name has been set!");
        } else if ((file.createNewFile() || true) && !file.canWrite()) {
            throw new IOException("Cannot write to file " + file.getAbsolutePath() + ". Is it read-only?");
        }
    } catch (IOException e) {
        throw new ConfigurationException(e.getMessage(), e);
    }
    log.debug("Saving {}", file.getAbsolutePath());

    final String fName = file.getName();
    try {
        int lastDot = fName.lastIndexOf('.');
        lastDot = lastDot > 0 ? lastDot : fName.length();

        final Path configPath = file.toPath();
        // Create a tmp file next to the original
        final Path tmp = Files.createTempFile(configPath.getParent(), fName.substring(0, lastDot) + ".",
                fName.substring(lastDot));
        try {
            Files.copy(configPath, tmp, StandardCopyOption.COPY_ATTRIBUTES,
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException iox) {
            log.error("Could not create temp-file {}: {}", tmp, iox.getMessage());
            throw iox;
        }
        log.trace("using temporary file: {}", tmp);
        // Save the config to the tmp file
        conf.save(tmp.toFile());

        log.trace("tmp saved, now replacing the original file: {}", configPath);
        // Replace the original with the tmp file
        try {
            try {
                Files.move(tmp, configPath, StandardCopyOption.REPLACE_EXISTING,
                        StandardCopyOption.ATOMIC_MOVE);
            } catch (AtomicMoveNotSupportedException amnx) {
                log.trace("atomic move not available: {}, trying without", amnx.getMessage());
                Files.move(tmp, configPath, StandardCopyOption.REPLACE_EXISTING);
            }
        } catch (IOException iox) {
            log.error("Could not write to {}, a backup was created in {}", configPath, tmp);
            throw iox;
        }
        log.info("configuration successfully saved to {}", configPath);
    } catch (final Throwable t) {
        throw new ConfigurationException("Unable to save the configuration to the file " + fName, t);
    }
}

From source file:Presentacion.FUsuarios.java

private void btnImagenMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnImagenMouseClicked

    try {/*  ww w  .ja  va2s .c o  m*/
        fc = new JFileChooser();
        fc.setAcceptAllFileFilterUsed(false); // No deja seleccionar todo tipo de archivos
        FileNameExtensionFilter filtroImagen = new FileNameExtensionFilter("Imgenes JPG, PNG & GIF", "jpg",
                "png", "gif");//Creo filtro para tipo de imagen
        fc.addChoosableFileFilter(filtroImagen);// Asigno el filtro creado de imagenes

        int returnVal = fc.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {

            String path = this.getClass().getResource("Imagenes").getPath();

            File file = fc.getSelectedFile();

            String extension = file.getName().substring((file.getName().lastIndexOf(".") + 1));
            userImgName = path + "\\" + txtNickName.getText() + ".jpg";
            File fileToSave = new File(userImgName);
            FileWriter fileWr = new FileWriter(fileToSave);
            fileWr.close();
            Files.copy(fc.getSelectedFile().toPath(), fileToSave.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (HeadlessException | IOException ex) {
        JOptionPane.showMessageDialog(this, "Error al cargar imagen", "Error", JOptionPane.ERROR_MESSAGE);
        System.out.println("Error en alta cliente: " + ex.getMessage());
    }
}

From source file:org.owasp.benchmark.score.BenchmarkScore.java

private static void generateVulnerabilityScorecards(Set<Report> toolResults, Set<String> catSet) {
    StringBuilder htmlForCommercialAverages = null;

    int commercialToolTotal = 0;
    int numberOfVulnCategories = 0;
    int commercialLowTotal = 0;
    int commercialAveTotal = 0;
    int commercialHighTotal = 0;

    for (String cat : catSet) {
        try {//from   w w  w . ja v  a2  s  .  c  o  m
            ScatterVulns scatter = ScatterVulns.generateComparisonChart(cat, toolResults, focus);
            String filename = "Benchmark_v" + benchmarkVersion + "_Scorecard_for_" + cat.replace(' ', '_');
            Path htmlfile = Paths.get(scoreCardDirName + "/" + filename + ".html");
            Files.copy(Paths.get(pathToScorecardResources + "vulntemplate.html"), htmlfile,
                    StandardCopyOption.REPLACE_EXISTING);
            String html = new String(Files.readAllBytes(htmlfile));
            String fullTitle = "OWASP Benchmark Scorecard for " + cat;

            html = html.replace("${image}", filename + ".png");
            html = html.replace("${title}", fullTitle);
            html = html.replace("${vulnerability}",
                    cat + " (CWE #" + BenchmarkScore.translateNameToCWE(cat) + ")");
            html = html.replace("${version}", benchmarkVersion);

            String table = generateVulnStatsTable(toolResults, cat);
            html = html.replace("${table}", table);

            Files.write(htmlfile, html.getBytes());

            // Now build up the commercial stats scorecard if there are at least 2 commercial tools
            if (scatter.getCommercialToolCount() > 1) {
                if (htmlForCommercialAverages == null) {
                    commercialToolTotal = scatter.getCommercialToolCount();
                    htmlForCommercialAverages = new StringBuilder();
                    htmlForCommercialAverages.append("<table class=\"table\">\n");
                    htmlForCommercialAverages.append("<tr>");
                    htmlForCommercialAverages.append("<th>Vulnerability Category</th>");
                    htmlForCommercialAverages.append("<th>Low Tool Type</th>");
                    htmlForCommercialAverages.append("<th>Low Score</th>");
                    htmlForCommercialAverages.append("<th>Ave Score</th>");
                    htmlForCommercialAverages.append("<th>High Score</th>");
                    htmlForCommercialAverages.append("<th>High Tool Type</th>");
                    htmlForCommercialAverages.append("</tr>\n");
                } // if 1st time through

                numberOfVulnCategories++;

                String style = "";
                htmlForCommercialAverages.append("<tr>");
                htmlForCommercialAverages.append("<td>" + cat + "</td>");
                htmlForCommercialAverages.append("<td>" + scatter.getCommercialLowToolType() + "</td>");
                if (scatter.getCommercialLow() <= 10)
                    style = "class=\"danger\"";
                else if (scatter.getCommercialLow() >= 50)
                    style = "class=\"success\"";
                htmlForCommercialAverages.append("<td " + style + ">" + scatter.getCommercialLow() + "</td>");
                commercialLowTotal += scatter.getCommercialLow();
                htmlForCommercialAverages.append("<td>" + scatter.getCommercialAve() + "</td>");
                commercialAveTotal += scatter.getCommercialAve();
                if (scatter.getCommercialHigh() <= 10)
                    style = "class=\"danger\"";
                else if (scatter.getCommercialHigh() >= 50)
                    style = "class=\"success\"";
                htmlForCommercialAverages.append("<td " + style + ">" + scatter.getCommercialHigh() + "</td>");
                commercialHighTotal += scatter.getCommercialHigh();
                htmlForCommercialAverages.append("<td>" + scatter.getCommercialHighToolType() + "</td>");
                htmlForCommercialAverages.append("</tr>\n");
            } // if more than 1 commercial tool

        } catch (IOException e) {
            System.out.println("Error generating vulnerability summaries: " + e.getMessage());
            e.printStackTrace();
        }
    } // end for loop

    // if we computed a commercial average, then add the last row to the table AND create the file and write the HTML to it.
    if (htmlForCommercialAverages != null) {

        htmlForCommercialAverages.append("<tr>");
        htmlForCommercialAverages
                .append("<td>Average across all categories for " + commercialToolTotal + " tools</td>");
        htmlForCommercialAverages.append("<td></td>");
        htmlForCommercialAverages.append("<td>"
                + new DecimalFormat("0.0").format((float) commercialLowTotal / (float) numberOfVulnCategories)
                + "</td>");
        htmlForCommercialAverages.append("<td>"
                + new DecimalFormat("0.0").format((float) commercialAveTotal / (float) numberOfVulnCategories)
                + "</td>");
        htmlForCommercialAverages.append("<td>"
                + new DecimalFormat("0.0").format((float) commercialHighTotal / (float) numberOfVulnCategories)
                + "</td>");
        htmlForCommercialAverages.append("<td></td>");
        htmlForCommercialAverages.append("</tr>\n");

        try {

            commercialAveScorecardFilename = "Benchmark_v" + benchmarkVersion
                    + "_Scorecard_for_Commercial_Tools";
            Path htmlfile = Paths.get(scoreCardDirName + "/" + commercialAveScorecardFilename + ".html");
            Files.copy(Paths.get(pathToScorecardResources + "commercialAveTemplate.html"), htmlfile,
                    StandardCopyOption.REPLACE_EXISTING);
            String html = new String(Files.readAllBytes(htmlfile));

            html = html.replace("${version}", benchmarkVersion);

            String table = htmlForCommercialAverages.toString();
            html = html.replace("${table}", table);

            Files.write(htmlfile, html.getBytes());
            System.out.println("Commercial average scorecard computed.");
        } catch (IOException e) {
            System.out.println("Error generating commercial scorecard: " + e.getMessage());
            e.printStackTrace();
        }
    } // end if
}

From source file:org.tinymediamanager.core.Utils.java

/**
 * Creates (or adds) a file to a ZIP//ww w  .  j a  v a2s .c  o m
 * 
 * @param zipFile
 *          Path of zip file
 * @param toBeAdded
 *          Path to be added
 * @param internalPath
 *          the location inside the ZIP like /aa/a.txt
 */
public static void createZip(Path zipFile, Path toBeAdded, String internalPath) {
    Map<String, String> env = new HashMap<>();
    try {
        // check if file exists
        env.put("create", String.valueOf(!Files.exists(zipFile)));
        // use a Zip filesystem URI
        URI fileUri = zipFile.toUri(); // here
        URI zipUri = new URI("jar:" + fileUri.getScheme(), fileUri.getPath(), null);
        // System.out.println(zipUri);
        // URI uri = URI.create("jar:file:"+zipLocation); // here creates the
        // zip
        // try with resource
        try (FileSystem zipfs = FileSystems.newFileSystem(zipUri, env)) {
            // Create internal path in the zipfs
            Path internalTargetPath = zipfs.getPath(internalPath);
            if (!Files.exists(internalTargetPath.getParent())) {
                // Create directory
                Files.createDirectory(internalTargetPath.getParent());
            }
            // copy a file into the zip file
            Files.copy(toBeAdded, internalTargetPath, StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (Exception e) {
        LOGGER.error("Failed to create zip file!" + e.getMessage());
    }
}

From source file:com.ut.healthelink.service.impl.transactionOutManagerImpl.java

/**
 * The 'beginOutputProcess' function will start the process to creating the target download transaction
 *
 * @param configDetails/* w  w  w. ja va 2  s.  co m*/
 * @param transaction
 * @param transportDetails
 * @param uploadedBatchDetails
 */
public int beginOutputProcess(transactionTarget transaction) throws Exception {

    try {
        int batchId = 0;

        batchUploads uploadedBatchDetails = transactionInManager
                .getBatchDetails(transaction.getbatchUploadId());

        configuration configDetails = configurationManager.getConfigurationById(transaction.getconfigId());

        configurationTransport transportDetails = configurationTransportManager
                .getTransportDetails(transaction.getconfigId());

        /* Check to see what outut transport method was set up */

        /* ERG */
        if (transportDetails.gettransportMethodId() == 2) {

            /* Generate the batch */
            /* (target configuration Details, transaction details, transport Details for target config, Source OrgId, Source Original Filename, mergeable) */
            try {
                batchId = generateBatch(configDetails, transaction, transportDetails,
                        uploadedBatchDetails.getOrgId(), uploadedBatchDetails.getoriginalFileName(), false);

                /* Update the status of the uploaded batch to  TBP (Target Batch Creating in process) (ID = 25) */
                transactionInManager.updateBatchStatus(batchId, 25, "");
            } catch (Exception e) {
                throw new Exception(
                        "Error occurred trying to generate a batch. transactionId: " + transaction.getId(), e);
            }

        } /* File Download || FTP || EMed-Apps */ else if (transportDetails.gettransportMethodId() == 1
                || transportDetails.gettransportMethodId() == 3
                || transportDetails.gettransportMethodId() == 5) {

            boolean createNewFile = true;

            /* 
             If the merge batches option is not checked create the batch right away
             */
            if (transportDetails.getmergeBatches() == false) {

                /* Generate the batch */
                /* (target configuration Details, transaction details, transport Details for target config, Source OrgId, Source Original Filename, mergeable) */
                try {
                    batchId = generateBatch(configDetails, transaction, transportDetails,
                            uploadedBatchDetails.getOrgId(), uploadedBatchDetails.getoriginalFileName(), false);

                    /* Update the status of the uploaded batch to  TBP (Target Batch Creating in process) (ID = 25) */
                    transactionInManager.updateBatchStatus(batchId, 25, "");
                } catch (Exception e) {
                    throw new Exception(
                            "Error occurred trying to generate a batch. transactionId: " + transaction.getId(),
                            e);
                }

            } else {

                /* We want to merge this transaction with the existing created batch if not yet opened (ID = 28) */
                /* 1. Need to see if a mergable batch exists for the org that hasn't been picked up yet */
                int mergeablebatchId = transactionOutDAO.findMergeableBatch(configDetails.getorgId());

                /* If no mergable batch is found create a new batch */
                if (mergeablebatchId == 0) {

                    /* Generate the batch */
                    /* (target configuration Details, transaction details, transport Details for target config, Source OrgId, Source Original Filename, mergeable) */
                    try {
                        batchId = generateBatch(configDetails, transaction, transportDetails,
                                uploadedBatchDetails.getOrgId(), uploadedBatchDetails.getoriginalFileName(),
                                true);

                        /* Update the status of the uploaded batch to  TBP (Target Batch Creating in process) (ID = 25) */
                        transactionInManager.updateBatchStatus(batchId, 25, "");
                    } catch (Exception e) {
                        throw new Exception("Error occurred trying to generate a batch. transactionId: "
                                + transaction.getId(), e);
                    }

                } else {

                    batchId = mergeablebatchId;

                    /* Need to upldate the transaction batchDLId to the new found batch Id */
                    transactionOutDAO.updateTransactionTargetBatchDLId(batchId, transaction.getId());

                    /* Need to add a new entry in the summary table (need to make sure we don't enter duplicates) */
                    batchDownloadSummary summary = new batchDownloadSummary();
                    summary.setbatchId(batchId);
                    summary.settargetConfigId(configDetails.getId());
                    summary.setmessageTypeId(configDetails.getMessageTypeId());
                    summary.settargetOrgId(configDetails.getorgId());
                    summary.settransactionTargetId(transaction.getId());
                    summary.setsourceOrgId(uploadedBatchDetails.getOrgId());

                    try {
                        transactionOutDAO.submitSummaryEntry(summary);
                    } catch (Exception e) {
                        throw new Exception("Error occurred submitting the batch summary. batchId: " + batchId,
                                e);
                    }

                    createNewFile = false;

                }

            }

            /* Generate the file according to transportDetails 
             * 1. we generate output file according to encoding in transportDetails
             * 2. we always save an encrypted copy to archivesOut
             * */
            try {
                boolean encryptMessage = false;
                // we only support base64 for now
                if (transportDetails.getEncodingId() == 2) {
                    encryptMessage = true;
                }
                String generatedFilePath = generateTargetFile(createNewFile, transaction.getId(), batchId,
                        transportDetails, encryptMessage);

                try {
                    //we get dl file info
                    batchDownloads batchDetails = getBatchDetails(batchId);

                    File generatedFile = new File(generatedFilePath);
                    //file extension
                    String fileExt = batchDetails.getoutputFIleName()
                            .substring(batchDetails.getoutputFIleName().lastIndexOf("."));

                    fileSystem fileSystem = new fileSystem();
                    File archiveFile = new File(
                            fileSystem.setPath(archivePath) + batchDetails.getutBatchName() + fileExt);

                    //we check to see if our file is encoded
                    if (!encryptMessage) {
                        //we encode here
                        String strEncodedFile = filemanager.encodeFileToBase64Binary(generatedFile);
                        if (archiveFile.exists()) {
                            archiveFile.delete();
                        }
                        filemanager.writeFile(archiveFile.getAbsolutePath(), strEncodedFile);
                    } else {
                        Files.copy(generatedFile.toPath(), archiveFile.toPath(),
                                StandardCopyOption.REPLACE_EXISTING);
                    }

                } catch (Exception e) {
                    throw new Exception(
                            "Error occurred trying to copy generated file to archiveOut -  batchId: " + batchId,
                            e);
                }
            } catch (Exception e) {
                throw new Exception("Error occurred trying to generate the batch file. batchId: " + batchId, e);
            }
        }

        /* Update the status of the transaction to PP (Pending Pickup) (ID = 18) */
        transactionInManager.updateTransactionStatus(transaction.getbatchUploadId(),
                transaction.gettransactionInId(), 0, 18);

        /* Update the status of the transaction target to PP (Pending Pickup) (ID = 18) */
        updateTransactionTargetStatusOutBound(0, transaction.getId(), 0, 18);

        /* Update the status of the uploaded batch to  TBP (Target Batch Created) (ID = 28) */
        transactionInManager.updateBatchStatus(transaction.getbatchUploadId(), 28, "");

        return batchId;
    } catch (Exception e) {
        throw new Exception("Error occurred during the process of generating output files. transactionId: "
                + transaction.getId(), e);
    }

}

From source file:org.tinymediamanager.core.Utils.java

/**
 * Unzips the specified zip file to the specified destination directory. Replaces any files in the destination, if they already exist.
 * /*ww  w.  ja  v  a 2 s. c  o  m*/
 * @param zipFile
 *          the name of the zip file to extract
 * @param destDir
 *          the directory to unzip to
 * @throws IOException
 */
public static void unzip(Path zipFile, final Path destDir) {
    Map<String, String> env = new HashMap<>();

    try {
        // if the destination doesn't exist, create it
        if (!Files.exists(destDir)) {
            Files.createDirectories(destDir);
        }

        // check if file exists
        env.put("create", String.valueOf(!Files.exists(zipFile)));
        // use a Zip filesystem URI
        URI fileUri = zipFile.toUri(); // here
        URI zipUri = new URI("jar:" + fileUri.getScheme(), fileUri.getPath(), null);

        try (FileSystem zipfs = FileSystems.newFileSystem(zipUri, env)) {
            final Path root = zipfs.getPath("/");

            // walk the zip file tree and copy files to the destination
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    final Path destFile = Paths.get(destDir.toString(), file.toString());
                    LOGGER.debug("Extracting file {} to {}", file, destFile);
                    Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    final Path dirToCreate = Paths.get(destDir.toString(), dir.toString());
                    if (!Files.exists(dirToCreate)) {
                        LOGGER.debug("Creating directory {}", dirToCreate);
                        Files.createDirectory(dirToCreate);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    } catch (Exception e) {
        LOGGER.error("Failed to create zip file!" + e.getMessage());
    }
}

From source file:processing.app.debug.Compiler.java

private void mergeSketchWithBootloaderIfAppropriate(String className, PreferencesMap prefs) throws IOException {
    if (!prefs.containsKey("bootloader.noblink") && !prefs.containsKey("bootloader.file")) {
        return;//from  www  .  j  a v  a2s  . c om
    }

    String buildPath = prefs.get("build.path");

    Path sketch;
    Path sketchInSubfolder = Paths.get(buildPath, "sketch", className + ".hex");
    Path sketchInBuildPath = Paths.get(buildPath, className + ".hex");
    if (Files.exists(sketchInSubfolder)) {
        sketch = sketchInSubfolder;
    } else if (Files.exists(sketchInBuildPath)) {
        sketch = sketchInBuildPath;
    } else {
        return;
    }

    String bootloaderNoBlink = prefs.get("bootloader.noblink");
    if (bootloaderNoBlink == null) {
        bootloaderNoBlink = prefs.get("bootloader.file");
    }

    Path bootloader = Paths.get(prefs.get("runtime.platform.path"), "bootloaders", bootloaderNoBlink);
    if (!Files.exists(bootloader)) {
        System.err.println(I18n.format(_("Bootloader file specified but missing: {0}"), bootloader));
        return;
    }

    Path mergedSketch;
    if ("sketch".equals(sketch.getParent().getFileName().toString())) {
        mergedSketch = Paths.get(buildPath, "sketch", className + ".with_bootloader.hex");
    } else {
        mergedSketch = Paths.get(buildPath, className + ".with_bootloader.hex");
    }

    Files.copy(sketch, mergedSketch, StandardCopyOption.REPLACE_EXISTING);

    new MergeSketchWithBooloader().merge(mergedSketch.toFile(), bootloader.toFile());
}

From source file:processing.app.debug.OldCompiler.java

private void mergeSketchWithBootloaderIfAppropriate(String className, PreferencesMap prefs) throws IOException {
    if (!prefs.containsKey("bootloader.noblink") && !prefs.containsKey("bootloader.file")) {
        return;//from  w ww  . j a  va  2s . co m
    }

    String buildPath = prefs.get("build.path");

    Path sketch;
    Path sketchInSubfolder = Paths.get(buildPath, "sketch", className + ".hex");
    Path sketchInBuildPath = Paths.get(buildPath, className + ".hex");
    if (Files.exists(sketchInSubfolder)) {
        sketch = sketchInSubfolder;
    } else if (Files.exists(sketchInBuildPath)) {
        sketch = sketchInBuildPath;
    } else {
        return;
    }

    String bootloaderNoBlink = prefs.get("bootloader.noblink");
    if (bootloaderNoBlink == null) {
        bootloaderNoBlink = prefs.get("bootloader.file");
    }

    Path bootloader = Paths.get(prefs.get("runtime.platform.path"), "bootloaders", bootloaderNoBlink);
    if (!Files.exists(bootloader)) {
        System.err.println(I18n.format(tr("Bootloader file specified but missing: {0}"), bootloader));
        return;
    }

    Path mergedSketch;
    if ("sketch".equals(sketch.getParent().getFileName().toString())) {
        mergedSketch = Paths.get(buildPath, "sketch", className + ".with_bootloader.hex");
    } else {
        mergedSketch = Paths.get(buildPath, className + ".with_bootloader.hex");
    }

    Files.copy(sketch, mergedSketch, StandardCopyOption.REPLACE_EXISTING);

    new MergeSketchWithBooloader().merge(mergedSketch.toFile(), bootloader.toFile());
}

From source file:org.multibit.file.FileHandler.java

/**
 * To support multiple users on the same machine, the checkpoints file is
 * copied to the user's application data directory when SparkBit is first used.
 * /*www .j a v a 2 s  . c o m*/
 * Thus each user has their own copy of the blockchain.
 */
public void copyCheckpointsResource(String destinationCheckpointsFilename) throws IOException {
    if (destinationCheckpointsFilename == null) {
        return;
    }

    File destinationCheckpoints = new File(destinationCheckpointsFilename);
    log.info("Copying bundled sparkbit.checkpoints to '" + destinationCheckpointsFilename + "'");
    InputStream link = getClass()
            .getResourceAsStream("/" + MultiBitService.getFilePrefix() + MultiBitService.CHECKPOINTS_SUFFIX); //sparkbit.checkpoints");
    int bytesAvailable = link.available();
    long bytesCopied = Files.copy(link, destinationCheckpoints.getAbsoluteFile().toPath(),
            StandardCopyOption.REPLACE_EXISTING);
    link.close();

    // Check all the data was copied.
    long destinationLength = destinationCheckpoints.length();
    if (bytesAvailable != destinationLength) {
        String errorText = "Checkpoints were not copied to user's application data directory correctly.\nThe source checkpoints is of length "
                + bytesAvailable + "\nbut the destination checkpoints '" + destinationCheckpointsFilename
                + "' is of length " + destinationLength;
        log.error(errorText);
        throw new FileHandlerException(errorText);
    }
}