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:io.specto.hoverfly.junit.HoverflyRule.java

@Override
protected void after() {

    if (hoverflyMode == CAPTURE) {
        LOGGER.info("Storing captured data");
        try {/*  w w w  .  j  a va 2 s  .c  om*/
            HttpURLConnection con = (HttpURLConnection) new URL(String.format(RECORDS_URL, adminPort))
                    .openConnection();
            con.setRequestMethod("GET");
            final Path path = Paths.get(serviceDataURI);
            Files.copy(con.getInputStream(), path);
        } catch (IOException e) {
            throw new RuntimeException("Unable to persist captured data", e);
        }
    }

    LOGGER.info("Destroying hoverfly process");
    startedProcess.getProcess().destroy();
    final File binary = binaryPath.toFile();
    if (binary.exists())
        binary.delete();
}

From source file:ms.safi.btsync.BTSyncApp.java

private void extractWinBtSync() {
    try {/*from w w w.  jav a  2s  .  c  o m*/
        URL url = getClass().getClassLoader().getResource("btsync-win.exe");
        InputStream in = url.openStream();

        Files.copy(in, btSyncExecutable.toPath());
        btSyncExecutable.setExecutable(true, false);
        btSyncExecutable.setReadable(true, false);
        btSyncExecutable.setWritable(true, false);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:at.nonblocking.cliwix.cli.CliwixCliClient.java

private static void doExport(String cliwixServerUrl, Options options) {
    waitForServerReady(cliwixServerUrl, options);

    String exportFolder = options.getExportFolder();
    if (exportFolder == null) {
        console.printlnError("Error: Property export.folder is required.");
        console.exit(EXIT_STATUS_FAIL);/*from  w  w  w.  j ava2s .c o m*/
        return;
    }

    File outputDir = null;
    try {
        outputDir = new File(exportFolder);
        outputDir.mkdirs();
    } catch (Exception e) {
        console.printlnError("Error: Invalid export folder: " + exportFolder);
        console.exit(EXIT_STATUS_FAIL);
        return;
    }

    JSONObject exportSettings = options.getExportSettings();

    JSONObject json = postJson(cliwixServerUrl, "/services/exports", exportSettings);
    JSONObject exportResult = (JSONObject) json.get("exportResult");
    String exportId = (String) exportResult.get("exportId");

    console.println("Export started. Id: " + exportId);

    boolean success = waitForImportExport(true, exportId, cliwixServerUrl, options);

    if (success) {
        console.println("Export succeeded.");

        String path = "/services/exports/" + exportId + "/zip";
        if (debug)
            console.println("Sending GET request: " + path);
        Response zipResponse = getHandler.get(cliwixServerUrl, path, cookieManager);
        handleError(zipResponse);

        File tempFile = null;
        try {
            tempFile = File.createTempFile("export", ".zip");
        } catch (IOException e) {
            if (debug)
                console.printStacktrace(e);
            console.printlnError("Error: Unable to create temporary zip file");
            console.exit(EXIT_STATUS_FAIL);
            return;
        }
        long fileLength = zipResponse.getContentLength();
        ProgressCallback progressCallback = new ProgressCallbackConsoleImpl(console);

        try (InputStream inputStream = zipResponse.getResponseStream();
                OutputStream outputStream = new FileOutputStream(tempFile)) {

            byte[] buffer = new byte[BaseHttpHandler.CHUNK_SIZE];
            long transferred = 0;
            int len = -1;
            while ((len = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
                transferred = transferred + len;
                progressCallback.bytesTransferred(transferred, fileLength);
            }

            progressCallback.bytesTransferred(fileLength, fileLength);

        } catch (IOException e) {
            if (debug)
                console.printStacktrace(e);
            console.printlnError("Error: " + e.getMessage());
            console.exit(EXIT_STATUS_FAIL);
        } finally {
            zipResponse.disconnect();
        }

        if (options.isExtractZip()) {
            try {
                ZipFile zip = new ZipFile(tempFile);
                zip.extractAll(outputDir.getAbsolutePath());
            } catch (ZipException e) {
                if (debug)
                    console.printStacktrace(e);
                console.printlnError("Error: Corrupt ZIP file");
                console.exit(EXIT_STATUS_FAIL);
            } finally {
                tempFile.delete();
            }
        } else {
            File targetFile = new File(outputDir, "export_" + exportId + ".zip");
            try (FileInputStream fis = new FileInputStream(tempFile)) {
                Files.copy(fis, targetFile.toPath());
            } catch (IOException e) {
                if (debug)
                    console.printStacktrace(e);
                console.printlnError("Error: " + e.getMessage());
                console.exit(EXIT_STATUS_FAIL);
            } finally {
                tempFile.delete();
            }
        }

        console.println("Export data written to: " + outputDir.getAbsolutePath());

    } else {
        console.printlnError("Export failed!");

        String path = "/services/exports/" + exportId + "/report";
        if (debug)
            console.println("Sending GET request: " + path);
        Response reportResponse = getHandler.get(cliwixServerUrl, path, cookieManager);
        handleError(reportResponse);

        File reportFile = new File(outputDir, "export-report.html");

        try (OutputStream outputStream = new FileOutputStream(reportFile)) {
            outputStream.write(reportResponse.getResponseAsString().getBytes("UTF-8"));
            console.println("Error report written to: " + reportFile.getAbsolutePath());

        } catch (IOException e) {
            if (debug)
                console.printStacktrace(e);
            console.printlnError("Error: No report found");
        } finally {
            reportResponse.disconnect();
        }
    }

    if (options.isExportDeleteOnServerAfterTransfer()) {
        Response deleteResponse = deleteHandler.delete(cliwixServerUrl, "/services/exports/" + exportId,
                cookieManager);
        if (deleteResponse.getStatusCode() == 200) {
            console.println("Successfully deleted export folder on server.");
        } else {
            console.printlnError("Failed to delete export folder on server!");
        }
    }

    if (!success) {
        console.exit(EXIT_STATUS_FAIL);
    }
}

From source file:com.romeikat.datamessie.core.base.util.FileUtil.java

private Path createZipFile(final String dir, String filename, final List<Path> files) throws IOException {
    filename = normalizeFilename(filename);
    // Create ZIP file
    Path zipFile = Paths.get(dir, filename + ".zip");
    zipFile = getNonExisting(zipFile);/*from w  w  w  .ja v  a2s.c om*/
    Files.createFile(zipFile);
    final URI zipUri = URI.create("jar:file:" + zipFile.toUri().getPath());
    Files.delete(zipFile);
    final Map<String, String> zipProperties = new HashMap<String, String>();
    zipProperties.put("create", "true");
    zipProperties.put("encoding", "UTF-8");
    final FileSystem zipFS = FileSystems.newFileSystem(zipUri, zipProperties);
    // Copy TXT files to ZIP file
    for (final Path file : files) {
        final Path fileToZip = file;
        final Path pathInZipfile = zipFS.getPath(file.getFileName().toString());
        Files.copy(fileToZip, pathInZipfile);
    }
    // Done
    zipFS.close();
    return zipFile;
}

From source file:com.github.zhanhb.ckfinder.download.PathPartial.java

/**
 * Serve the specified resource, optionally including the data content.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param content Should the content be included?
 * @param path the resource to serve//from w  ww.ja v  a  2  s.  c o m
 *
 * @exception IOException if an input/output error occurs
 */
private void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content, Path path)
        throws IOException, ServletException {
    ActionContext context = new ActionContext().put(HttpServletRequest.class, request)
            .put(HttpServletResponse.class, response).put(ServletContext.class, request.getServletContext())
            .put(Path.class, path);
    if (path == null) {
        notFound.handle(context);
        return;
    }
    BasicFileAttributes attr;
    try {
        attr = Files.readAttributes(path, BasicFileAttributes.class);
    } catch (IOException ex) {
        notFound.handle(context);
        return;
    }
    context.put(BasicFileAttributes.class, attr);

    boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST;
    // Check if the conditions specified in the optional If headers are
    // satisfied.
    // Checking If headers
    boolean included = (request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH) != null);
    String etag = this.eTag.getValue(context);
    if (!included && !isError && !checkIfHeaders(request, response, attr, etag)) {
        return;
    }
    // Find content type.
    String contentType = contentTypeResolver.getValue(context);
    // Get content length
    long contentLength = attr.size();
    // Special case for zero length files, which would cause a
    // (silent) ISE
    boolean serveContent = content && contentLength != 0;
    Range[] ranges = null;
    if (!isError) {
        if (useAcceptRanges) {
            // Accept ranges header
            response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
        }
        // Parse range specifier
        ranges = serveContent ? parseRange(request, response, attr, etag) : FULL;
        // ETag header
        response.setHeader(HttpHeaders.ETAG, etag);
        // Last-Modified header
        response.setDateHeader(HttpHeaders.LAST_MODIFIED, attr.lastModifiedTime().toMillis());
    }
    ServletOutputStream ostream = null;
    if (serveContent) {
        ostream = response.getOutputStream();
    }

    String disposition = contentDisposition.getValue(context);
    if (disposition != null) {
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, disposition);
    }

    // Check to see if a Filter, Valve of wrapper has written some content.
    // If it has, disable range requests and setting of a content length
    // since neither can be done reliably.
    if (isError || ranges == FULL) {
        // Set the appropriate output headers
        if (contentType != null) {
            log.debug("serveFile: contentType='{}'", contentType);
            response.setContentType(contentType);
        }
        if (contentLength >= 0) {
            setContentLengthLong(response, contentLength);
        }
        // Copy the input stream to our output stream (if requested)
        if (serveContent) {
            log.trace("Serving bytes");
            Files.copy(path, ostream);
        }
    } else if (ranges != null && ranges.length != 0) {
        // Partial content response.
        response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
        if (ranges.length == 1) {
            Range range = ranges[0];
            response.addHeader(HttpHeaders.CONTENT_RANGE, range.toString());
            long length = range.end - range.start + 1;
            setContentLengthLong(response, length);
            if (contentType != null) {
                log.debug("serveFile: contentType='{}'", contentType);
                response.setContentType(contentType);
            }
            if (serveContent) {
                try (InputStream stream = Files.newInputStream(path)) {
                    copyRange(stream, ostream, range, new byte[Math.min((int) length, 8192)]);
                }
            }
        } else {
            response.setContentType("multipart/byteranges; boundary=" + MIME_SEPARATION);
            if (serveContent) {
                copy(path, ostream, ranges, contentType, new byte[Math.min((int) contentLength, 8192)]);
            }
        }
    }
}

From source file:com.liferay.sync.engine.SyncSystemTest.java

protected void addFolder(Path testFilePath, JsonNode stepJsonNode) throws Exception {

    SyncSite syncSite = getSyncSite(stepJsonNode);

    String dependency = getString(stepJsonNode, "dependency");

    final Path dependencyFilePath = getDependencyFilePath(testFilePath, dependency);

    FileSystem fileSystem = FileSystems.getDefault();

    final Path targetFilePath = Paths.get(FileUtil.getFilePathName(syncSite.getFilePathName(),
            dependency.replace("common" + fileSystem.getSeparator(), "")));

    Files.walkFileTree(dependencyFilePath, new SimpleFileVisitor<Path>() {

        @Override/*from  w  w  w .j a v a2  s.co  m*/
        public FileVisitResult preVisitDirectory(Path filePath, BasicFileAttributes basicFileAttributes)
                throws IOException {

            Path relativeFilePath = dependencyFilePath.relativize(filePath);

            Files.createDirectories(targetFilePath.resolve(relativeFilePath));

            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path filePath, BasicFileAttributes basicFileAttributes)
                throws IOException {

            Path relativeFilePath = dependencyFilePath.relativize(filePath);

            Files.copy(filePath, targetFilePath.resolve(relativeFilePath));

            return FileVisitResult.CONTINUE;
        }

    });
}

From source file:com.github.zhanhb.ckfinder.connector.handlers.command.FileUploadCommand.java

/**
 * saves temporary file in the correct file path.
 *
 * @param path path to save file//  w w w . ja  v  a2 s.com
 * @param item file upload item
 * @param param the parameter
 * @param context ckfinder context
 * @throws IOException when IO Exception occurs.
 * @throws ConnectorException when error occurs
 */
private void saveTemporaryFile(Path path, MultipartFile item, FileUploadParameter param,
        CKFinderContext context) throws IOException, ConnectorException {
    Path file = getPath(path, param.getNewFileName());

    if (ImageUtils.isImageExtension(file)) {
        if (!context.isCheckSizeAfterScaling() && !ImageUtils.checkImageSize(item, context)) {
            param.throwException(ErrorCode.UPLOADED_TOO_BIG);
        }
        ImageUtils.createTmpThumb(item, file, getFileItemName(item), context);
        if (context.isCheckSizeAfterScaling()
                && !FileUtils.isFileSizeInRange(param.getType(), Files.size(file))) {
            Files.deleteIfExists(file);
            param.throwException(ErrorCode.UPLOADED_TOO_BIG);
        }
    } else {
        try (InputStream in = item.getInputStream()) {
            Files.copy(in, file);
        }
    }
    FileUploadEvent args = new FileUploadEvent(param.getCurrentFolder(), file);
    context.fireOnFileUpload(args);
}

From source file:ms.safi.btsync.BTSyncApp.java

private void extractLinuxBtSync() {
    try {//from  ww w .j a  va 2 s.  c  o m
        URL url = getClass().getClassLoader().getResource("btsync-linux-i386");
        InputStream in = url.openStream();

        Files.copy(in, btSyncExecutable.toPath());
        btSyncExecutable.setExecutable(true, false);
        btSyncExecutable.setReadable(true, false);
        btSyncExecutable.setWritable(true, false);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:fr.ortolang.diffusion.store.binary.BinaryStoreServiceBean.java

@Override
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public String put(InputStream content) throws BinaryStoreServiceException, DataCollisionException {
    try {//  www  .ja va2s  . c  o m
        HashedFilterInputStream input = factory.getHashedFilterInputStream(content);
        try {
            Path tmpfile = Paths.get(working.toString(), Long.toString(System.nanoTime()));

            Files.copy(input, tmpfile);
            LOGGER.log(Level.FINE, "content stored in local temporary file: " + tmpfile.toString());
            String hash = input.getHash();
            LOGGER.log(Level.FINE, "content based generated sha1 hash: " + hash);

            String digit = hash.substring(0, DISTINGUISH_SIZE);
            Path volume = Paths.get(base.toString(), BinaryStoreVolumeMapper.getVolume(digit));
            Path parent = Paths.get(base.toString(), BinaryStoreVolumeMapper.getVolume(digit), digit);
            Path file = Paths.get(base.toString(), BinaryStoreVolumeMapper.getVolume(digit), digit, hash);
            if (!Files.exists(volume)) {
                Files.createDirectory(volume);
            }
            if (!Files.exists(parent)) {
                Files.createDirectory(parent);
            }
            if (!Files.exists(file)) {
                Files.move(tmpfile, file);
                LOGGER.log(Level.FINE, "content moved in local definitive file: " + file.toString());
            } else {
                LOGGER.log(Level.FINE, "a file with same hash already exists, trying to detect collision");
                try (InputStream input1 = Files.newInputStream(file);
                        InputStream input2 = Files.newInputStream(tmpfile)) {
                    if (IOUtils.contentEquals(input1, input2)) {
                        Files.delete(tmpfile);
                    } else {
                        LOGGER.log(Level.SEVERE,
                                "BINARY COLLISION DETECTED - storing colliding files in dedicated folder");
                        Files.copy(file, Paths.get(collide.toString(), hash + ".origin"));
                        Files.move(tmpfile, Paths.get(collide.toString(), hash + ".colliding"));
                        throw new DataCollisionException();
                    }
                }
            }
            return hash;
        } catch (IOException | VolumeNotFoundException e) {
            throw new BinaryStoreServiceException(e);
        } finally {
            IOUtils.closeQuietly(input);
        }
    } catch (NoSuchAlgorithmException e) {
        throw new BinaryStoreServiceException(e);
    }
}

From source file:UploadTest.java

@Test
public void put_data_test() {
    String pid = "frl:6376979";
    try {/*ww  w.ja va  2s .  c o m*/
        System.out.println(url);
        String charset = "UTF-8";
        File file = new File("/home/raul/test/frl%3A6376984/6376986.pdf");
        FileInputStream fi = new FileInputStream(file);

        httpCon.setDoOutput(true);
        httpCon.setDoInput(true);
        httpCon.setRequestMethod("PUT");
        httpCon.setRequestProperty("Connection", "Keep-Alive");
        httpCon.setRequestProperty("Content-Type", "application/pdf");
        httpCon.setRequestProperty("type", "multipart/form-data");
        httpCon.setRequestProperty("Accept", "application/data");
        httpCon.setRequestProperty("uploaded_file", file.getPath());
        System.out.println(file.getPath());
        DataOutputStream out = new DataOutputStream(httpCon.getOutputStream());
        System.out.println("130");
        Files.copy(file.toPath(), out);
        int bytesRead;
        byte[] dataBuffer = new byte[1024];
        while ((bytesRead = fi.read(dataBuffer)) != -1) {
            out.write(dataBuffer, 0, bytesRead);
        }
        System.out.println("137");
        out.flush();
        out.close();
        System.out.println("140");
        System.out.println("142");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}