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:de.cebitec.readXplorer.differentialExpression.plot.DeSeq2GraphicsTopComponent.java

private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
    ReadXplorerFileChooser fc = new ReadXplorerFileChooser(new String[] { "svg" }, "svg") {
        private static final long serialVersionUID = 1L;

        @Override/*w  ww. j  a v  a 2  s. c  o m*/
        public void save(String fileLocation) {
            ProgressHandle progressHandle = ProgressHandleFactory
                    .createHandle("Save plot to svg file: " + fileLocation);
            Path to = FileSystems.getDefault().getPath(fileLocation, "");
            DeSeq2AnalysisHandler.Plot selectedPlot = (DeSeq2AnalysisHandler.Plot) plotType.getSelectedItem();
            Path from = currentlyDisplayed.toPath();
            try {
                Path outputFile = Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
                messages.setText("SVG image saved to " + outputFile.toString());
            } catch (IOException ex) {
                Date currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "{0}: " + ex.getMessage(),
                        currentTimestamp);
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Could not write to file.",
                        JOptionPane.WARNING_MESSAGE);
            } finally {
                progressHandle.switchToDeterminate(100);
                progressHandle.finish();
            }

        }

        @Override
        public void open(String fileLocation) {
        }
    };
    fc.openFileChooser(ReadXplorerFileChooser.SAVE_DIALOG);
}

From source file:com.cloudbees.clickstack.util.Files2.java

public static void unzip(@Nonnull Path zipFile, @Nonnull final Path destDir) throws RuntimeIOException {
    try {/*from w ww  .  ja  v a2  s.  co  m*/
        //if the destination doesn't exist, create it
        if (Files.notExists(destDir)) {
            logger.trace("Create dir: {}", destDir);
            Files.createDirectories(destDir);
        }

        try (FileSystem zipFileSystem = createZipFileSystem(zipFile, false)) {
            final Path root = zipFileSystem.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 {
                    try {
                        final Path destFile = Paths.get(destDir.toString(), file.toString());
                        logger.trace("Extract file {} to {}", file, destDir);
                        Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
                    } catch (IOException | RuntimeException e) {
                        logger.warn("Exception copying file '" + file + "' to '" + destDir + "', ignore file",
                                e);
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    final Path dirToCreate = Paths.get(destDir.toString(), dir.toString());

                    if (Files.notExists(dirToCreate)) {
                        logger.trace("Create dir {}", dirToCreate);
                        try {
                            Files.createDirectory(dirToCreate);
                        } catch (IOException e) {
                            logger.warn("Exception creating directory '" + dirToCreate + "' for '" + dir
                                    + "', ignore dir subtree", e);
                            return FileVisitResult.SKIP_SUBTREE;
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    } catch (IOException e) {
        throw new RuntimeIOException("Exception expanding " + zipFile + " to " + destDir, e);
    }
}

From source file:edu.usu.sdl.openstorefront.service.SystemServiceImpl.java

@Override
public void saveGeneralMedia(GeneralMedia generalMedia, InputStream fileInput) {
    Objects.requireNonNull(generalMedia);
    Objects.requireNonNull(fileInput);
    Objects.requireNonNull(generalMedia.getName(), "Name must be set.");

    generalMedia.setFileName(generalMedia.getName());
    try (InputStream in = fileInput) {
        Files.copy(in, generalMedia.pathToMedia(), StandardCopyOption.REPLACE_EXISTING);
        generalMedia.populateBaseCreateFields();
        persistenceService.persist(generalMedia);
    } catch (IOException ex) {
        throw new OpenStorefrontRuntimeException("Unable to store media file.",
                "Contact System Admin.  Check file permissions and disk space ", ex);
    }/*ww  w  .j a v  a2 s .com*/
}

From source file:it.baeyens.arduino.managers.Manager.java

/**
 * downloads an archive file from the internet and saves it in the download
 * folder under the name "pArchiveFileName" then extrats the file to
 * pInstallPath if pForceDownload is true the file will be downloaded even
 * if the download file already exists if pForceDownload is false the file
 * will only be downloaded if the download file does not exists The
 * extraction is done with processArchive so only files types supported by
 * this method will be properly extracted
 * /*from   w  w w. java 2  s . com*/
 * @param pURL
 *            the url of the file to download
 * @param pArchiveFileName
 *            the name of the file in the download folder
 * @param pInstallPath
 * @param pForceDownload
 * @param pMonitor
 * @return
 */
public static IStatus downloadAndInstall(String pURL, String pArchiveFileName, Path pInstallPath,
        boolean pForceDownload, IProgressMonitor pMonitor) {
    IPath dlDir = ConfigurationPreferences.getInstallationPathDownload();
    IPath archivePath = dlDir.append(pArchiveFileName);
    String archiveFullFileName = archivePath.toString();
    try {
        URL dl = new URL(pURL);
        dlDir.toFile().mkdir();
        if (!archivePath.toFile().exists() || pForceDownload) {
            pMonitor.subTask("Downloading " + pArchiveFileName + " .."); //$NON-NLS-1$ //$NON-NLS-2$
            Files.copy(dl.openStream(), Paths.get(archivePath.toString()), StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (IOException e) {
        return new Status(IStatus.ERROR, Activator.getId(), Messages.Manager_Failed_to_download + pURL, e);
    }
    return processArchive(pArchiveFileName, pInstallPath, pForceDownload, archiveFullFileName, pMonitor);
}

From source file:nl.coinsweb.sdk.FileManager.java

public static Path placeAttachment(String internalRef, Path attachment) {
    Path fileName = attachment.getFileName();
    Path homePath = getTempZipPath().resolve(internalRef);
    Path attachmentPath = homePath.resolve(ATTACHMENT_PATH);
    Path absoluteTempPath = attachmentPath.resolve(fileName);
    try {//from  w  w w. j  a  v a 2s  .  c o m
        Files.copy(attachment, absoluteTempPath, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
    return absoluteTempPath;
}

From source file:codes.thischwa.c5c.impl.LocalConnector.java

@Override
public void replace(String backendPath, InputStream in) throws C5CException {
    Path file = buildRealPath(backendPath);
    try {//w w  w .j a  v a  2s. c o  m
        Files.copy(in, file, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new FilemanagerException(FilemanagerAction.REPLACE, FilemanagerException.Key.InvalidFileUpload,
                file.getFileName().toString());
    }
}

From source file:de.cebitec.readXplorer.differentialExpression.plot.DeSeqGraphicsTopComponent.java

private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
    ReadXplorerFileChooser fc = new ReadXplorerFileChooser(new String[] { "svg" }, "svg") {
        private static final long serialVersionUID = 1L;

        @Override/* w w  w  .  j  a va  2 s  .  c o  m*/
        public void save(String fileLocation) {
            ProgressHandle progressHandle = ProgressHandleFactory
                    .createHandle("Save plot to svg file: " + fileLocation);
            Path to = FileSystems.getDefault().getPath(fileLocation, "");
            DeSeqAnalysisHandler.Plot selectedPlot = (DeSeqAnalysisHandler.Plot) plotType.getSelectedItem();
            if (selectedPlot == DeSeqAnalysisHandler.Plot.MAplot) {
                saveToSVG(fileLocation);
            } else {
                Path from = currentlyDisplayed.toPath();
                try {
                    Path outputFile = Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
                    messages.setText("SVG image saved to " + outputFile.toString());
                } catch (IOException ex) {
                    Date currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime());
                    Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "{0}: " + ex.getMessage(),
                            currentTimestamp);
                    JOptionPane.showMessageDialog(null, ex.getMessage(), "Could not write to file.",
                            JOptionPane.WARNING_MESSAGE);
                } finally {
                    progressHandle.switchToDeterminate(100);
                    progressHandle.finish();
                }
            }
        }

        @Override
        public void open(String fileLocation) {
        }
    };
    fc.openFileChooser(ReadXplorerFileChooser.SAVE_DIALOG);
}

From source file:com.upplication.s3fs.util.AmazonS3ClientMock.java

@Override
public CopyObjectResult copyObject(String sourceBucketName, String sourceKey, String destinationBucketName,
        String destinationKey) throws AmazonClientException {
    Path src = find(sourceBucketName, sourceKey);
    if (src != null && Files.exists(src)) {
        Path bucket = find(destinationBucketName);
        Path dest = bucket.resolve(destinationKey.replaceAll("/", "%2F"));
        try {/*w  ww  .  ja  va 2 s.  c  o m*/
            Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new AmazonServiceException("Problem copying mock objects: ", e);
        }

        return new CopyObjectResult();
    }

    throw new AmazonServiceException("object source not found");
}

From source file:io.lavagna.web.api.CardDataController.java

@ExpectPermission(Permission.CREATE_FILE)
@RequestMapping(value = "/api/card/{cardId}/file", method = RequestMethod.POST)
@ResponseBody//  www .  j  a va  2s.c o m
public List<String> uploadFiles(@PathVariable("cardId") int cardId,
        @RequestParam("files") List<MultipartFile> files, User user, HttpServletResponse resp)
        throws IOException {

    LOG.debug("Files uploaded: {}", files.size());

    if (!ensureFileSize(files)) {
        resp.setStatus(422);
        return Collections.emptyList();
    }

    List<String> digests = new ArrayList<>();
    for (MultipartFile file : files) {
        Path p = Files.createTempFile("lavagna", "upload");
        try (InputStream fileIs = file.getInputStream()) {
            Files.copy(fileIs, p, StandardCopyOption.REPLACE_EXISTING);
            String digest = DigestUtils.sha256Hex(Files.newInputStream(p));
            String contentType = file.getContentType() != null ? file.getContentType()
                    : "application/octet-stream";
            boolean result = cardDataService.createFile(file.getOriginalFilename(), digest, file.getSize(),
                    cardId, Files.newInputStream(p), contentType, user, new Date()).getLeft();
            if (result) {
                LOG.debug("file uploaded! size: {}, original name: {}, content-type: {}", file.getSize(),
                        file.getOriginalFilename(), file.getContentType());
                digests.add(digest);
            }
        } finally {
            Files.delete(p);
            LOG.debug("deleted temp file {}", p);
        }
    }
    eventEmitter.emitUploadFile(cardRepository.findBy(cardId).getColumnId(), cardId);
    return digests;
}

From source file:cc.arduino.Compiler.java

private void saveHex(String compiledSketch, String copyOfCompiledSketch, PreferencesMap prefs)
        throws RunnerException {
    try {/*  w w  w .  j  a  v  a  2 s  .c om*/
        compiledSketch = StringReplacer.replaceFromMapping(compiledSketch, prefs);
        copyOfCompiledSketch = StringReplacer.replaceFromMapping(copyOfCompiledSketch, prefs);
        copyOfCompiledSketch = copyOfCompiledSketch.replaceAll(":", "_");

        Path compiledSketchPath;
        Path compiledSketchPathInSubfolder = Paths.get(prefs.get("build.path"), "sketch", compiledSketch);
        Path compiledSketchPathInBuildPath = Paths.get(prefs.get("build.path"), compiledSketch);
        if (Files.exists(compiledSketchPathInSubfolder)) {
            compiledSketchPath = compiledSketchPathInSubfolder;
        } else if (Files.exists(compiledSketchPathInBuildPath)) {
            compiledSketchPath = compiledSketchPathInBuildPath;
        } else {
            return;
        }

        Path copyOfCompiledSketchFilePath = Paths.get(this.sketch.getFolder().getAbsolutePath(),
                copyOfCompiledSketch);

        Files.copy(compiledSketchPath, copyOfCompiledSketchFilePath, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new RunnerException(e);
    }
}