Example usage for java.nio.file Files copy

List of usage examples for java.nio.file Files copy

Introduction

In this page you can find the example usage for java.nio.file Files copy.

Prototype

public static long copy(InputStream in, Path target, CopyOption... options) throws IOException 

Source Link

Document

Copies all bytes from an input stream to a file.

Usage

From source file:com.hpe.application.automation.tools.pc.PcClient.java

public boolean downloadTrendReportAsPdf(String trendReportId, String directory) throws PcException {

    try {/*from ww w.ja  v  a2s. c om*/
        logger.println("Downloading trend report: " + trendReportId + " in PDF format");
        InputStream in = restProxy.getTrendingPDF(trendReportId);
        File dir = new File(directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String filePath = directory + IOUtils.DIR_SEPARATOR + "trendReport" + trendReportId + ".pdf";
        Path destination = Paths.get(filePath);
        Files.copy(in, destination, StandardCopyOption.REPLACE_EXISTING);
        logger.println("Trend report: " + trendReportId + " was successfully downloaded");
    } catch (Exception e) {

        logger.println("Failed to download trend report: " + e.getMessage());
        throw new PcException(e.getMessage());
    }

    return true;

}

From source file:com.netflix.genie.agent.execution.statemachine.actions.SetUpJobAction.java

private File createJobEnvironmentFile(final File jobDirectory, final List<File> setUpFiles,
        final Map<String, String> serverProvidedEnvironment, final Map<String, String> extraEnvironment)
        throws SetUpJobException {
    final Path genieDirectory = PathUtils.jobGenieDirectoryPath(jobDirectory);
    final Path envScriptPath = PathUtils.composePath(genieDirectory,
            JobConstants.GENIE_AGENT_ENV_SCRIPT_RESOURCE);
    final Path envScriptLogPath = PathUtils.composePath(genieDirectory, JobConstants.LOGS_PATH_VAR,
            JobConstants.GENIE_AGENT_ENV_SCRIPT_LOG_FILE_NAME);
    final Path envScriptOutputPath = PathUtils.composePath(genieDirectory,
            JobConstants.GENIE_AGENT_ENV_SCRIPT_OUTPUT_FILE_NAME);

    // Copy env script from resources to genie directory
    try {//  w w w  .ja va2  s.  c om
        Files.copy(new ClassPathResource(JobConstants.GENIE_AGENT_ENV_SCRIPT_RESOURCE).getInputStream(),
                envScriptPath, StandardCopyOption.REPLACE_EXISTING);
        // Make executable
        envScriptPath.toFile().setExecutable(true, true);
    } catch (final IOException e) {
        throw new SetUpJobException("Could not copy environment script resource: ", e);
    }

    // Set up process that executes the script
    final ProcessBuilder processBuilder = new ProcessBuilder().inheritIO();

    processBuilder.environment().putAll(serverProvidedEnvironment);
    processBuilder.environment().putAll(extraEnvironment);

    final List<String> commandArgs = Lists.newArrayList(envScriptPath.toString(),
            envScriptOutputPath.toString(), envScriptLogPath.toString());

    setUpFiles.forEach(f -> commandArgs.add(f.getAbsolutePath()));

    processBuilder.command(commandArgs);

    // Run the setup script
    final int exitCode;
    try {
        exitCode = processBuilder.start().waitFor();
    } catch (final IOException e) {
        throw new SetUpJobException("Could not execute environment setup script", e);
    } catch (final InterruptedException e) {
        throw new SetUpJobException("Interrupted while waiting for environment setup script", e);
    }

    if (exitCode != 0) {
        throw new SetUpJobException("Non-zero exit code from environment setup script: " + exitCode);
    }

    // Check and return the output file
    final File envScriptOutputFile = envScriptOutputPath.toFile();

    if (!envScriptOutputFile.exists()) {
        throw new SetUpJobException("Expected output file does not exist: " + envScriptOutputPath.toString());
    }

    return envScriptOutputFile;
}

From source file:io.hops.hopsworks.api.zeppelin.server.ZeppelinConfig.java

private boolean copyBinDir() throws IOException {
    String source = settings.getZeppelinDir() + File.separator + "bin";
    File binDir = new File(binDirPath);
    File sourceDir = new File(source);
    if (binDir.list().length == sourceDir.list().length) {
        //should probably check if the files are the same
        return false;
    }//  w  ww. j av  a 2 s. c  om
    Path destinationPath;
    for (File file : sourceDir.listFiles()) {
        destinationPath = Paths.get(binDirPath + File.separator + file.getName());
        Files.copy(file.toPath(), destinationPath, StandardCopyOption.REPLACE_EXISTING);
    }
    return binDir.list().length == sourceDir.list().length;
}

From source file:controladores.InscripcionBean.java

public void guardarArchivos() {

    try {//from  ww  w  . ja  va  2s.  c  o  m

        for (SelectItem i : items) {
            if (i.getValue().toString().equals(idMaestria)) {
                descripcionMaetria = i.getLabel();
            }
        }
        PromocionDao pD = new PromocionDao();
        descripcionPromo = pD.getPromocion(idPromo).getDescripcion().toString();

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dateobj = new Date();
        String nombreCarpeta = (descripcionMaetria + "-" + descripcionPromo + "-" + estudiante.getApellidos()
                + " " + estudiante.getNombres() + "-" + df.format(dateobj).replaceAll(":", "-")).trim();
        File directorio = new File("c:/Postgrado/inscripciones/requisitos/" + nombreCarpeta + "/");
        if (!directorio.exists()) {
            directorio.mkdirs();
        }
        int cont = 0;
        ArchivosDao aDao = new ArchivosDao();
        for (UploadedFile f : files) {
            filename = reqPro.get(cont).getRequisitos().getFormato();
            extension = FilenameUtils.getExtension(f.getFileName());
            Path ruta = Paths.get(directorio + "/" + filename + "." + extension);
            InputStream input = f.getInputstream();
            Files.copy(input, ruta, StandardCopyOption.REPLACE_EXISTING);
            archivos = new Archivos();
            archivos.setRuta(ruta.toString());
            archivos.setRequisitosPromo(reqPro.get(cont));
            archivos.setSolicitudInscripcion(sInscripcion);
            aDao.insertar(archivos);
            cont++;
        }

        // resultado= "/faces/index?faces-redirect=true";
    } catch (IOException ex) {
        Logger.getLogger(InscripcionBean.class.getName()).log(Level.SEVERE, null, ex);
        FacesMessage message = new FacesMessage("Error", ex.toString());
        FacesContext.getCurrentInstance().addMessage(null, message);
        //resultado ="";
    } catch (Exception ex) {
        Logger.getLogger(InscripcionBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    files.clear();

}

From source file:com.collaborne.jsonschema.generator.pojo.PojoGenerator.java

@VisibleForTesting
protected void writeSource(URI type, ClassName className, Buffer buffer) throws IOException {
    // Create the file based on the className in the mapping
    Path outputFile = getClassSourceFile(className);
    logger.info("{}: Writing {}", type, outputFile);

    // Write stuff into it
    Files.createDirectories(outputFile.getParent());
    Files.copy(buffer.getInputStream(), outputFile, StandardCopyOption.REPLACE_EXISTING);
}

From source file:fr.moribus.imageonmap.migration.V3Migrator.java

/**
 * Makes a standard file copy, and checks the integrity of the destination 
 * file after the copy/*from   ww w .  ja  va  2s .  c  o m*/
 * @param sourceFile The file to copy
 * @param destinationFile The destination file
 * @throws IOException If the copy failed, if the integrity check failed, or if the destination file already exists
 */
static private void verifiedBackupCopy(File sourceFile, File destinationFile) throws IOException {
    if (destinationFile.exists())
        throw new IOException(
                "Backup copy failed : destination file (" + destinationFile.getName() + ") already exists.");

    long sourceSize = sourceFile.length();
    String sourceCheckSum = fileCheckSum(sourceFile, "SHA1");

    Path sourcePath = Paths.get(sourceFile.getAbsolutePath());
    Path destinationPath = Paths.get(destinationFile.getAbsolutePath());
    Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);

    long destinationSize = destinationFile.length();
    String destinationCheckSum = fileCheckSum(destinationFile, "SHA1");

    if (sourceSize != destinationSize || !sourceCheckSum.equals(destinationCheckSum)) {
        throw new IOException("Backup copy failed : source and destination files (" + sourceFile.getName()
                + ") differ after copy.");
    }

}

From source file:com.xse.optstack.persconftool.base.persistence.PersConfExport.java

private static void copyDefaultDataFiles(final File targetBaseFolder, final EApplication application,
        final Function<EConfiguration, EDefaultData> defaultDataProvider) {
    for (final EResource eResource : application.getResources()) {
        // copy default data files in case we have a file-based default data configuration with new file refs
        if (eResource.getConfiguration().getType() == EDefaultDataType.FILE) {
            final EDefaultData factoryDefaultData = defaultDataProvider.apply(eResource.getConfiguration());
            if (!StringUtils.isEmpty(factoryDefaultData.getLocalResourcePath())) {
                final File dataFile = new File(factoryDefaultData.getLocalResourcePath());
                if (dataFile.exists() && dataFile.canRead()) {
                    try {
                        final Path source = Paths.get(dataFile.toURI());
                        final Path target = Paths.get(new File(
                                targetBaseFolder.getAbsolutePath() + File.separator + eResource.getName())
                                        .toURI());
                        Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
                    } catch (final IOException | IllegalArgumentException | SecurityException e) {
                        Logger.error(Activator.PLUGIN_ID,
                                "Error copying factory default file to target location: " + eResource.getName(),
                                e);//  w  w w .j  a  v a2  s .  co  m
                    }
                } else {
                    Logger.warn(Activator.PLUGIN_ID, "Invalid factory default data path!");
                }
            }
        }
    }
}

From source file:dialog.DialogFunctionRoom.java

private void btnFunctionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFunctionActionPerformed
    String roomName = tfRoomName.getText();
    if (roomName.isEmpty()) {
        JOptionPane.showMessageDialog(null, "Tn phng khng c  trng", "Error",
                JOptionPane.ERROR_MESSAGE);
        tfRoomName.requestFocus();//from  w  w  w .  ja  va 2  s  . com
        return;
    }
    String priceString = tfPrice.getText();
    if (priceString.isEmpty()) {
        JOptionPane.showMessageDialog(null, "Gi phng khng c  trng", "Error",
                JOptionPane.ERROR_MESSAGE);
        tfPrice.requestFocus();
        return;
    }
    double price;
    try {
        price = Double.parseDouble(priceString);
    } catch (NumberFormatException nfe) {
        JOptionPane.showMessageDialog(null, "Gi phng khng ng nh dng", "Error",
                JOptionPane.ERROR_MESSAGE);
        return;
    }
    int max;
    try {
        max = Integer.parseInt(priceString);
    } catch (NumberFormatException nfe) {
        JOptionPane.showMessageDialog(null, "Gi phng khng ng nh dng", "Error",
                JOptionPane.ERROR_MESSAGE);
        return;
    }

    Floor objFloor = (Floor) cbFloor.getSelectedItem();
    int roomType = cbRoomType.getSelectedIndex() + 1;
    ModelPicture modelPicture = new ModelPicture();
    if (mType == Constant.TYPE_ADD) {
        if (mControllerRoom == null) {
            actionAddNoController();
            return;
        }
        String idRoom = UUID.randomUUID().toString();
        if (!mControllerRoom.isExistRoomInFloor(roomName, objFloor.getIdFloor())) {
            mListUriPhotos.stream().forEach((uriPicture) -> {
                File file = new File(uriPicture);
                String fileName = FilenameUtils.getBaseName(file.getName()) + "-" + System.nanoTime() + "."
                        + FilenameUtils.getExtension(file.getName());
                Path source = Paths.get(uriPicture);
                Path destination = Paths.get("files/" + fileName);
                try {
                    Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
                } catch (IOException ex) {
                    Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex);
                }
                Picture objPicture = new Picture(UUID.randomUUID().toString(), idRoom, fileName);
                modelPicture.addItem(objPicture);
                mListPictures.add(objPicture);
            });
            Room objRoom = new Room(idRoom, objFloor.getIdFloor(), roomName, roomType, price,
                    Constant.ROOM_CONDITION_AVAILABLE_TYPE, mListPictures, null, objFloor.getFloorName(), max);
            mObjRoom = objRoom;
            if (mControllerRoom.addItem(objRoom)) {
                objFloor.setMaxRoom(objFloor.getMaxRoom() + 1);
                new ModelFloor().editItem(objFloor);
                ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png").getPath());
                JOptionPane.showMessageDialog(this, "Thm thnh cng!", "Success",
                        JOptionPane.INFORMATION_MESSAGE, icon);
                this.dispose();
            }
        } else {
            JOptionPane.showMessageDialog(this, "Phng  tn ti!", "Error", JOptionPane.ERROR_MESSAGE);
        }
    } else if (mType == Constant.TYPE_EDIT) {
        mObjRoom.setFloorName(objFloor.getFloorName());
        mObjRoom.setRoomName(roomName);
        mObjRoom.setPrice(price);
        mObjRoom.setIdFloor(objFloor.getIdFloor());
        mObjRoom.setMax(max);
        mObjRoom.setType(cbRoomType.getSelectedIndex() + 1);
        mListUriPhotos.stream().forEach((uriPicture) -> {
            File file = new File(uriPicture);
            String fileName = FilenameUtils.getBaseName(file.getName()) + "-" + System.nanoTime() + "."
                    + FilenameUtils.getExtension(file.getName());
            Path source = Paths.get(uriPicture);
            Path destination = Paths.get("files/" + fileName);
            try {
                Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException ex) {
                Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex);
            }
            Picture objPicture = new Picture(UUID.randomUUID().toString(), mObjRoom.getIdRoom(), fileName);
            modelPicture.addItem(objPicture);
            mListPictures.add(objPicture);
        });
        mObjRoom.setListPicture(mListPictures);
        if (mControllerRoom.editItem(mObjRoom, mRow)) {
            ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png").getPath());
            JOptionPane.showMessageDialog(this, "Sa thnh cng!", "Success",
                    JOptionPane.INFORMATION_MESSAGE, icon);
            this.dispose();
        }
    }
}

From source file:fr.inria.soctrace.tools.ocelotl.core.caches.DataCache.java

/**
 * Save the cache of the current trace to the specified path
 * //from   w ww  .  jav a  2 s.  c  o m
 * @param oParam
 *            current parameters
 * @param destPath
 *            path to save the file
 */
public void saveDataCacheTo(OcelotlParameters oParam, String destPath) {
    // Get the current cache file
    CacheParameters params = new CacheParameters(oParam);
    File source = null;

    // Look for the corresponding file
    for (CacheParameters par : cachedData.keySet()) {
        if (similarParameters(params, par)) {
            source = cachedData.get(par);
        }
    }

    if (source != null) {
        File dest = new File(destPath);

        try {
            Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        logger.error("No corresponding cache file was found");
    }
}