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(Path source, OutputStream out) throws IOException 

Source Link

Document

Copies all bytes from a file to an output stream.

Usage

From source file:controladores.prueba.java

public void guardar() {
    try {/* ww  w  .j  a  v a 2 s  .  c  o m*/

        for (Part pa : archivos) {
            Path destino = Paths.get("d:/temp/" + archivo.getSubmittedFileName());
            InputStream bytes = null;
            if (archivo != null) {
                bytes = archivo.getInputStream();
                Files.copy(bytes, destino);
                FacesMessage message = new FacesMessage("Succesful", " is uploaded.");
                FacesContext.getCurrentInstance().addMessage(null, message);

            }
        }
    } catch (Exception ex) {
        FacesMessage message = new FacesMessage("Succesful", ex.toString());
        FacesContext.getCurrentInstance().addMessage(null, message);
    }
}

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

private void backupFile() throws IOException {
    final Path sourceFile = picture.getFile();
    final String parentPath = sourceFile.getParent().toString();
    final String hashedPath = DigestUtils.md5Hex(parentPath + backupId);

    final Path targetDir = BACKUP_DIR.resolve(hashedPath);
    Files.createDirectories(targetDir);

    Files.copy(sourceFile, targetDir.resolve(sourceFile.getFileName()));
}

From source file:org.hawk.http.HTTPManager.java

@Override
public File importFiles(String path, File temp) {
    try (CloseableHttpClient cl = createClient()) {
        try (CloseableHttpResponse response = cl.execute(new HttpGet(repositoryURL))) {
            Files.copy(response.getEntity().getContent(), temp.toPath());
            return temp;
        }//from   w  w  w .  j a  v a  2 s  . c  om
    } catch (IOException e) {
        console.printerrln(e);
        return null;
    }
}

From source file:modmanager.backend.ModificationOption.java

/**
 * Installs given source file//  w ww . ja  va 2s  .c om
 *
 * @param file
 */
protected void install(File file) {
    logger.log(Level.INFO, "Installing {0} ...", file.getAbsolutePath());

    File destination = getDestinationFile(file);

    /**
     * Make necessary directories
     */
    destination.getParentFile().mkdirs();

    try {
        /**
         * Copy files
         */
        Files.copy(file.toPath(), destination.toPath());
    } catch (IOException ex) {
        logger.log(Level.WARNING, "Could not copy to {0}", destination.getAbsolutePath());
    }
}

From source file:com.squareup.wire.schema.internal.parser.RpcMethodScanner.java

private List<RpcMethodDefinition> inspectProtoFile(InputStream instream, String serviceName)
        throws IOException {
    File tempFile = File.createTempFile("proto", null);
    tempFile.delete();//from   w  w  w  . j a  v a  2s  .  c  o  m
    Files.copy(instream, tempFile.toPath());
    SixtProtoParser parser = new SixtProtoParser(tempFile, serviceName);
    List<RpcMethodDefinition> methodDefinitions = parser.getRpcMethods();
    tempFile.delete();
    instream.close();
    return methodDefinitions;
}

From source file:org.elasticsearch.plugins.PluginManagerIT.java

/** creates a plugin .zip and returns the url for testing */
private String createPlugin(final Path structure, String... properties) throws IOException {
    writeProperties(structure, properties);
    Path zip = createTempDir().resolve(structure.getFileName() + ".zip");
    try (ZipOutputStream stream = new ZipOutputStream(Files.newOutputStream(zip))) {
        Files.walkFileTree(structure, new SimpleFileVisitor<Path>() {
            @Override/*  w w w  .j a va  2s  .  co m*/
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                stream.putNextEntry(new ZipEntry(structure.relativize(file).toString()));
                Files.copy(file, stream);
                return FileVisitResult.CONTINUE;
            }
        });
    }
    if (randomBoolean()) {
        writeSha1(zip, false);
    } else if (randomBoolean()) {
        writeMd5(zip, false);
    }
    return zip.toUri().toURL().toString();
}

From source file:org.apache.flink.tests.util.FlinkDistribution.java

public void copyOptJarsToLib(String jarNamePrefix) throws FileNotFoundException, IOException {
    final Optional<Path> reporterJarOptional;
    try (Stream<Path> logFiles = Files.walk(opt)) {
        reporterJarOptional = logFiles.filter(path -> path.getFileName().toString().startsWith(jarNamePrefix))
                .findFirst();/*from w ww.j  a  va2  s.  c  o  m*/
    }
    if (reporterJarOptional.isPresent()) {
        final Path optReporterJar = reporterJarOptional.get();
        final Path libReporterJar = lib.resolve(optReporterJar.getFileName());
        Files.copy(optReporterJar, libReporterJar);
        filesToDelete.add(new AutoClosablePath(libReporterJar));
    } else {
        throw new FileNotFoundException("No jar could be found matching the pattern " + jarNamePrefix + ".");
    }
}

From source file:pinterestbackup.PINDownloader.java

/**
 * This method retrieve a pin connecting via HTTP to URLSource and copy the content
 * to the specified pathSave./*w w w  . ja va2  s  . c o  m*/
 * 
 * @param pin
 * @param pinPath: Path to save
 * @throws pinterestbackup.exceptions.PinCopyException
 */
public void savePinToFile(PinterestPin pin, Path pinPath) throws PinCopyException {
    HttpGet httpgetImg = new HttpGet();
    CloseableHttpClient httpclient = HttpClients.createDefault();

    if (pinPath == null)
        return;

    //Check if file exists
    if (this.localFiles.containsKey(pinPath.toString())) {
        //if (Files.exists(pinPath)){
        logPIN.log(Level.INFO, "Board {0} PIN {1} already exists.",
                new Object[] { board.getName(), pin.getUrl() });
        return;
    }

    logPIN.log(Level.INFO, "Save Board {0} PIN {1} to path.", new Object[] { board.getName(), pin.getUrl() });

    try {
        URI uri = new URI(pin.getUrl());
        httpgetImg.setURI(uri);
        CloseableHttpResponse response = httpclient.execute(httpgetImg);
        try (InputStream instream = response.getEntity().getContent()) {
            Files.copy(instream, pinPath);
        }
    } catch (IOException | URISyntaxException ex) {
        throw new PinCopyException(ex.getMessage());
    }
}

From source file:com.streamsets.datacollector.MiniSDCTestingUtility.java

/**
 * Start mini SDC//from   ww w .java  2  s .com
 * @param executionMode the Execution mode - could be standalone or cluster
 * @return
 * @throws Exception
 */
public MiniSDC createMiniSDC(ExecutionMode executionMode) throws Exception {
    Properties miniITProps = new Properties();
    File miniITProperties = new File(Resources.getResource("miniIT.properties").toURI());
    InputStream sdcInStream = new FileInputStream(miniITProperties);
    miniITProps.load(sdcInStream);
    String sdcDistRoot = (String) miniITProps.get(SDC_DIST_DIR);
    File sdcDistFile = new File(sdcDistRoot);
    if (!sdcDistFile.exists()) {
        throw new RuntimeException("SDC dist root dir " + sdcDistFile.getAbsolutePath() + "doesn't exist");
    }
    LOG.info("SDC dist root at " + sdcDistFile.getAbsolutePath());
    sdcInStream.close();

    File target = getDataTestDir();
    String targetRoot = target.getAbsolutePath();
    File etcTarget = new File(target, "etc");
    File resourcesTarget = new File(target, "resources");
    FileUtils.copyDirectory(new File(sdcDistRoot + "/etc"), etcTarget);
    FileUtils.copyDirectory(new File(sdcDistRoot + "/resources"), resourcesTarget);
    FileUtils.copyDirectory(new File(sdcDistRoot + "/libexec"), new File(target, "libexec"));
    // Set execute permissions back on script
    Set<PosixFilePermission> set = new HashSet<PosixFilePermission>();
    set.add(PosixFilePermission.OWNER_EXECUTE);
    set.add(PosixFilePermission.OWNER_READ);
    set.add(PosixFilePermission.OWNER_WRITE);
    set.add(PosixFilePermission.OTHERS_READ);
    Files.setPosixFilePermissions(new File(target, "libexec" + "/_cluster-manager").toPath(), set);
    File staticWebDir = new File(target, "static-web");
    staticWebDir.mkdir();

    setExecutePermission(new File(target, "libexec" + "/_cluster-manager").toPath());
    File log4jProperties = new File(etcTarget, "sdc-log4j.properties");
    if (log4jProperties.exists()) {
        log4jProperties.delete();
    }
    Files.copy(Paths.get(Resources.getResource("log4j.properties").toURI()), log4jProperties.toPath());

    File sdcProperties = new File(etcTarget, "sdc.properties");
    System.setProperty("sdc.conf.dir", etcTarget.getAbsolutePath());
    System.setProperty("sdc.resources.dir", resourcesTarget.getAbsolutePath());
    System.setProperty("sdc.libexec.dir", targetRoot + "/libexec");
    System.setProperty("sdc.static-web.dir", targetRoot + "/static-web");
    rewriteProperties(sdcProperties, executionMode);
    this.miniSDC = new MiniSDC(sdcDistRoot);
    return this.miniSDC;
}

From source file:gob.dp.simco.registro.controller.VictimaViolenciaController.java

private void remonbrarArchivo() {
    if (file1.getSize() > 0) {
        DateFormat fechaHora = new SimpleDateFormat("yyyyMMddHHmmss");
        String formato = fechaHora.format(new Date());
        String ruta = formato + getFileExtension(getFilename(file1));
        File file = new File(ConstantesUtil.FILE_SYSTEM + ruta);
        try (InputStream input = file1.getInputStream()) {
            Files.copy(input, file.toPath());
        } catch (IOException ex) {
            log.error(ex);//from   w  ww  . j  a v  a  2s.  c o m
        }
        actividadVictima.setRuta(ruta);
    }
}