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:dotaSoundEditor.Controls.EditorPanel.java

protected File promptUserForNewFile(String wavePath) {
    JFileChooser chooser = new JFileChooser(new File(UserPrefs.getInstance().getWorkingDirectory()));
    FileNameExtensionFilter filter = new FileNameExtensionFilter("MP3s and WAVs", "mp3", "wav");
    chooser.setAcceptAllFileFilterUsed((false));
    chooser.setFileFilter(filter);// www.j  a  va2 s  .c om
    chooser.setMultiSelectionEnabled(false);

    int chooserRetVal = chooser.showOpenDialog(chooser);
    if (chooserRetVal == JFileChooser.APPROVE_OPTION) {
        DefaultMutableTreeNode selectedFile = (DefaultMutableTreeNode) getTreeNodeFromWavePath(wavePath);
        Path chosenFile = Paths.get(chooser.getSelectedFile().getAbsolutePath());
        //Strip caps and spaces out of filenames. The item sound parser seems to have trouble with them.
        String destFileName = chosenFile.getFileName().toString().toLowerCase().replace(" ", "_");
        Path destPath = Paths.get(installDir, "/dota/sound/" + getCustomSoundPathString() + destFileName);
        UserPrefs.getInstance().setWorkingDirectory(chosenFile.getParent().toString());

        try {
            new File(destPath.toString()).mkdirs();
            Files.copy(chosenFile, destPath, StandardCopyOption.REPLACE_EXISTING);

            String waveString = selectedFile.getUserObject().toString();
            int startIndex = -1;
            int endIndex = -1;
            if (waveString.contains("\"wave\"")) {
                startIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 2);
                endIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 3);
            } else //Some wavestrings don't have the "wave" at the beginning for some reason
            {
                startIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 0);
                endIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 1);
            }

            String waveStringFilePath = waveString.substring(startIndex, endIndex + 1);
            waveString = waveString.replace(waveStringFilePath,
                    "\"" + getCustomSoundPathString() + destFileName + "\"");
            selectedFile.setUserObject(waveString);

            //Write out modified tree to scriptfile.
            ScriptParser parser = new ScriptParser(this.currentTreeModel);
            String scriptString = getCurrentScriptString();
            Path scriptPath = Paths.get(scriptString);
            parser.writeModelToFile(scriptPath.toString());

            //Update UI
            ((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent()).setUserObject(waveString);
            ((DefaultTreeModel) currentTree.getModel())
                    .nodeChanged((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent());
            JOptionPane.showMessageDialog(this, "Sound file successfully replaced.");

        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Unable to replace sound.\nDetails: " + ex.getMessage(),
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    return null;
}

From source file:com.rover12421.shaka.apktool.lib.AndrolibResourcesAj.java

/**
 * ?aapt`declared here is not defined`//  ww w  .  j  a v a 2 s .  c o  m
 * @param errInfo
 * @param rootDir
 */
private boolean fuckNotDefinedRes(String errInfo, String rootDir) {
    if (ShakaBuildOption.getInstance().isFuckNotDefinedRes()) {
        //Public symbol drawable/? declared here is not defined.
        Pattern patternRes = Pattern.compile("Public symbol (.+?) declared here is not defined");
        Matcher matcherRes = patternRes.matcher(errInfo);
        while (matcherRes.find()) {
            String res = matcherRes.group(1);
            String fileName = "res/" + res + ".xml";
            LogHelper.warning("Add temp res : " + fileName);
            notDefinedRes.add(fileName);
        }

        if (notDefinedRes.size() > 0) {
            for (String resName : notDefinedRes) {
                Path des = Paths.get(rootDir + File.separator + resName);
                // ??
                des.toFile().getParentFile().mkdirs();
                InputStream is = this.getClass().getResourceAsStream(SHAKA_XML);
                try {
                    Files.copy(is, des, StandardCopyOption.REPLACE_EXISTING);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                IOUtils.closeQuietly(is);
            }

            return true;
        }
    }
    return false;
}

From source file:controladores.prueba.java

public void handleFileUpload(FileUploadEvent event) {

    UploadedFile file = event.getFile();
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date dateobj = new Date();
    String nombreFecha = (df.format(dateobj).replaceAll(":", "-"));
    Path path = Paths.get("D:\\Postgrado\\inscripciones\\requisitos\\" + nombreFecha.trim());
    //if directory exists?
    if (!Files.exists(path)) {
        try {//from   w ww . j  a  va  2  s. co m
            Files.createDirectories(path);
        } catch (IOException e) {
            //fail to create directory
            e.printStackTrace();
        }
    }
    String filename = file.getFileName();
    //         String extension = f.getContentType();
    Path ruta = Paths.get(path + "\\" + filename);

    try (InputStream input = file.getInputstream()) {
        Files.copy(input, ruta, StandardCopyOption.REPLACE_EXISTING);
        FacesMessage message = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, message);
    } catch (IOException ex) {
        Logger.getLogger(prueba.class.getName()).log(Level.SEVERE, null, ex);
        FacesMessage message = new FacesMessage("Succesful", ex.toString());
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

}

From source file:ddf.catalog.impl.operations.OperationsMetacardSupport.java

void generateMetacardAndContentItems(List<ContentItem> incomingContentItems, Map<String, Metacard> metacardMap,
        List<ContentItem> contentItems, Map<String, Map<String, Path>> tmpContentPaths) throws IngestException {
    for (ContentItem contentItem : incomingContentItems) {
        try {//from  w ww.ja va  2 s.c om
            Path tmpPath = null;
            String fileName;
            long size;
            try (InputStream inputStream = contentItem.getInputStream()) {
                fileName = contentItem.getFilename();
                if (inputStream == null) {
                    throw new IngestException("Could not copy bytes of content message.  Message was NULL.");
                }

                if (!InputValidation.isFileNameClientSideSafe(fileName)) {
                    throw new IngestException("Ignored filename found.");
                }

                String sanitizedFilename = InputValidation.sanitizeFilename(fileName);
                tmpPath = Files.createTempFile(FilenameUtils.getBaseName(sanitizedFilename),
                        FilenameUtils.getExtension(sanitizedFilename));
                Files.copy(inputStream, tmpPath, StandardCopyOption.REPLACE_EXISTING);
                size = Files.size(tmpPath);

                final String key = contentItem.getId();
                Map<String, Path> pathAndQualifiers = tmpContentPaths.get(key);

                if (pathAndQualifiers == null) {
                    pathAndQualifiers = new HashMap<>();
                    pathAndQualifiers.put(contentItem.getQualifier(), tmpPath);
                    tmpContentPaths.put(key, pathAndQualifiers);
                } else {
                    pathAndQualifiers.put(contentItem.getQualifier(), tmpPath);
                }

            } catch (IOException e) {
                if (tmpPath != null) {
                    FileUtils.deleteQuietly(tmpPath.toFile());
                }
                throw new IngestException("Could not copy bytes of content message.", e);
            }
            String mimeTypeRaw = contentItem.getMimeTypeRawData();
            mimeTypeRaw = guessMimeType(mimeTypeRaw, fileName, tmpPath);

            if (!InputValidation.isMimeTypeClientSideSafe(mimeTypeRaw)) {
                throw new IngestException("Unsupported mime type.");
            }

            // If any sanitization was done, rename file name to sanitized file name.
            if (!InputValidation.sanitizeFilename(fileName).equals(fileName)) {
                fileName = InputValidation.sanitizeFilename(fileName);
            } else {
                fileName = updateFileExtension(mimeTypeRaw, fileName);
            }

            Metacard metacard;
            boolean qualifiedContent = StringUtils.isNotEmpty(contentItem.getQualifier());
            if (qualifiedContent) {
                metacard = contentItem.getMetacard();
            } else {
                metacard = metacardFactory.generateMetacard(mimeTypeRaw, contentItem.getId(), fileName,
                        tmpPath);
            }
            metacardMap.put(metacard.getId(), metacard);

            ContentItem generatedContentItem = new ContentItemImpl(metacard.getId(),
                    qualifiedContent ? contentItem.getQualifier() : "",
                    com.google.common.io.Files.asByteSource(tmpPath.toFile()), mimeTypeRaw, fileName, size,
                    metacard);
            contentItems.add(generatedContentItem);
        } catch (Exception e) {
            tmpContentPaths.values().stream().flatMap(id -> id.values().stream())
                    .forEach(path -> FileUtils.deleteQuietly(path.toFile()));
            tmpContentPaths.clear();
            throw new IngestException("Could not create metacard.", e);
        }
    }
}

From source file:net.codestory.simplelenium.driver.Downloader.java

protected void unzip(File zip, File toDir) throws IOException {
    try (ZipFile zipFile = new ZipFile(zip)) {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                continue;
            }/*from  ww  w .j a v a  2  s  . co  m*/

            File to = new File(toDir, entry.getName());

            File parent = to.getParentFile();
            if (!parent.exists()) {
                if (!parent.mkdirs()) {
                    throw new IOException("Unable to create folder " + parent);
                }
            }

            try (InputStream input = zipFile.getInputStream(entry)) {
                Files.copy(input, to.toPath(), REPLACE_EXISTING);
            }
        }
    }
}

From source file:com.netflix.spinnaker.halyard.backup.services.v1.BackupService.java

private void untarHalconfig(String halconfigDir, String halconfigTar) {
    FileInputStream tarInput = null;
    TarArchiveInputStream tarArchiveInputStream = null;

    try {/*from  w  w w  . java 2  s  . co  m*/
        tarInput = new FileInputStream(new File(halconfigTar));
        tarArchiveInputStream = (TarArchiveInputStream) new ArchiveStreamFactory()
                .createArchiveInputStream("tar", tarInput);

    } catch (IOException | ArchiveException e) {
        throw new HalException(Problem.Severity.FATAL, "Failed to open backup: " + e.getMessage(), e);
    }

    try {
        ArchiveEntry archiveEntry = tarArchiveInputStream.getNextEntry();
        while (archiveEntry != null) {
            String entryName = archiveEntry.getName();
            Path outputPath = Paths.get(halconfigDir, entryName);
            File outputFile = outputPath.toFile();
            if (!outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            }

            if (archiveEntry.isDirectory()) {
                outputFile.mkdir();
            } else {
                Files.copy(tarArchiveInputStream, outputPath, REPLACE_EXISTING);
            }

            archiveEntry = tarArchiveInputStream.getNextEntry();
        }
    } catch (IOException e) {
        throw new HalException(Problem.Severity.FATAL, "Failed to read archive entry: " + e.getMessage(), e);
    }
}

From source file:com.netflix.nicobar.example.groovy2.GroovyModuleLoaderExample.java

private static void deployTestArchive(ArchiveRepository repository) throws IOException {
    InputStream archiveJarIs = GroovyModuleLoaderExample.class.getClassLoader()
            .getResourceAsStream(ARCHIVE_JAR_NAME);
    Path archiveToDeploy = Files.createTempFile(SCRIPT_MODULE_ID, ".jar");
    Files.copy(archiveJarIs, archiveToDeploy, StandardCopyOption.REPLACE_EXISTING);
    IOUtils.closeQuietly(archiveJarIs);/*w ww  . jav  a 2s. com*/
    JarScriptArchive jarScriptArchive = new JarScriptArchive.Builder(archiveToDeploy).build();
    repository.insertArchive(jarScriptArchive);
}

From source file:business.services.FileService.java

public File uploadPart(User user, String name, File.AttachmentType type, MultipartFile file, Integer chunk,
        Integer chunks, String flowIdentifier) {
    try {/*w w  w  . j  a v  a 2s .  com*/
        String identifier = user.getId().toString() + "_" + flowIdentifier;
        String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        log.info("File content-type: " + file.getContentType());
        try {
            contentType = MediaType.valueOf(file.getContentType()).toString();
            log.info("Media type: " + contentType);
        } catch (InvalidMediaTypeException e) {
            log.warn("Invalid content type: " + e.getMediaType());
            //throw new FileUploadError("Invalid content type: " + e.getMediaType());
        }
        InputStream input = file.getInputStream();

        // Create temporary file for chunk
        Path path = fileSystem.getPath(uploadPath).normalize();
        if (!path.toFile().exists()) {
            Files.createDirectory(path);
        }
        name = URLEncoder.encode(name, "utf-8");

        String prefix = getBasename(name);
        String suffix = getExtension(name);
        Path f = Files.createTempFile(path, prefix, suffix + "." + chunk + ".chunk").normalize();
        // filter path names that point to places outside the upload path.
        // E.g., to prevent that in cases where clients use '../' in the filename
        // arbitrary locations are reachable.
        if (!Files.isSameFile(path, f.getParent())) {
            // Path f is not in the upload path. Maybe 'name' contains '..'?
            throw new FileUploadError("Invalid file name");
        }
        log.info("Copying file to " + f.toString());

        // Copy chunk to temporary file
        Files.copy(input, f, StandardCopyOption.REPLACE_EXISTING);

        // Save chunk location in chunk map
        SortedMap<Integer, Path> chunkMap;
        synchronized (uploadChunks) {
            // FIXME: perhaps use a better identifier? Not sure if this one 
            // is unique enough...
            chunkMap = uploadChunks.get(identifier);
            if (chunkMap == null) {
                chunkMap = new TreeMap<Integer, Path>();
                uploadChunks.put(identifier, chunkMap);
            }
        }
        chunkMap.put(chunk, f);
        log.info("Chunk " + chunk + " saved to " + f.toString());

        // Assemble complete file if all chunks have been received
        if (chunkMap.size() == chunks.intValue()) {
            uploadChunks.remove(identifier);
            Path assembly = Files.createTempFile(path, prefix, suffix).normalize();
            // filter path names that point to places outside the upload path.
            // E.g., to prevent that in cases where clients use '../' in the filename
            // arbitrary locations are reachable.
            if (!Files.isSameFile(path, assembly.getParent())) {
                // Path assembly is not in the upload path. Maybe 'name' contains '..'?
                throw new FileUploadError("Invalid file name");
            }
            log.info("Assembling file " + assembly.toString() + " from " + chunks + " chunks...");
            OutputStream out = Files.newOutputStream(assembly, StandardOpenOption.CREATE,
                    StandardOpenOption.APPEND);

            // Copy chunks to assembly file, delete chunk files
            for (int i = 1; i <= chunks; i++) {
                //log.info("Copying chunk " + i + "...");
                Path source = chunkMap.get(new Integer(i));
                if (source == null) {
                    log.error("Cannot find chunk " + i);
                    throw new FileUploadError("Cannot find chunk " + i);
                }
                Files.copy(source, out);
                Files.delete(source);
            }

            // Save assembled file name to database
            log.info("Saving attachment to database...");
            File attachment = new File();
            attachment.setName(URLDecoder.decode(name, "utf-8"));
            attachment.setType(type);
            attachment.setMimeType(contentType);
            attachment.setDate(new Date());
            attachment.setUploader(user);
            attachment.setFilename(assembly.getFileName().toString());
            attachment = fileRepository.save(attachment);
            return attachment;
        }
        return null;
    } catch (IOException e) {
        log.error(e);
        throw new FileUploadError(e.getMessage());
    }
}

From source file:com.tocsi.images.ReceivedImageController.java

public void handleFileUpload(FileUploadEvent event) {
    if (event.getFile() != null) {
        try {//from   w  w w .j a va2s.co  m
            UploadedFile uf = (UploadedFile) event.getFile();
            File folder = new File(GlobalsBean.destOriginal);
            //File folderThumb = new File(destThumbnail);
            String filename = FilenameUtils.getBaseName(uf.getFileName());
            String extension = FilenameUtils.getExtension(uf.getFileName());
            File file = File.createTempFile(filename + "-", "." + extension, folder);
            //File fileThumb = File.createTempFile(filename + "-", "." + extension, folderThumb);

            //resize image here
            BufferedImage originalImage = ImageIO.read(uf.getInputstream());
            InputStream is = uf.getInputstream();
            if (originalImage.getWidth() > 700) { //resize image if image's width excess 700px
                BufferedImage origImage = Scalr.resize(originalImage, Scalr.Method.QUALITY,
                        Scalr.Mode.FIT_TO_WIDTH, 640,
                        (int) ((originalImage.getHeight() / ((double) (originalImage.getWidth() / 700.0)))),
                        Scalr.OP_ANTIALIAS);
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(origImage, extension, os);
                is = new ByteArrayInputStream(os.toByteArray());
            }

            //create thumbnail
            BufferedImage thumbnail = Scalr.resize(ImageIO.read(uf.getInputstream()), 150);
            ByteArrayOutputStream osThumb = new ByteArrayOutputStream();
            ImageIO.write(thumbnail, extension, osThumb);
            InputStream isThumbnail = new ByteArrayInputStream(osThumb.toByteArray());

            try (InputStream input = is) {
                Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }

            try (InputStream input = isThumbnail) {
                Files.copy(input, Paths.get(GlobalsBean.destThumbnail + GlobalsBean.separator + file.getName()),
                        StandardCopyOption.REPLACE_EXISTING);
            }

            //File chartFile = new File(file.getAbsolutePath());
            //chart = new DefaultStreamedContent(new FileInputStream(chartFile), "image/jpg");
            ImageBean ib = new ImageBean();
            ib.setFilename(file.getName());
            ib.setThumbFile(file.getName());
            ib.setImageFileLocation(GlobalsBean.destOriginal + GlobalsBean.separator + file.getName());
            imageList.add(ib);

        } catch (IOException | IllegalArgumentException | ImagingOpException ex) {
            Utilities.displayError(ex.getMessage());
        }
    }
}

From source file:de.unirostock.sems.caroweb.Converter.java

private void run(HttpServletRequest request, HttpServletResponse response, String uploadedName, String[] req,
        File tmp, File out, Path STORAGE) throws ServletException, IOException {
    cleanUp();//  ww  w.java2s . c o m

    uploadedName.replaceAll("[^A-Za-z0-9 ]", "_");
    if (uploadedName.length() < 3)
        uploadedName += "container";

    CaRoConverter conv = null;

    if (req[1].equals("caro"))
        conv = new CaToRo(tmp);
    else if (req[1].equals("roca"))
        conv = new RoToCa(tmp);
    else {
        error(request, response, "do not know what to do");
        return;
    }
    conv.convertTo(out);

    List<CaRoNotification> notifications = conv.getNotifications();

    Path result = null;
    if (out.exists()) {
        result = Files.createTempFile(STORAGE, uploadedName,
                "-converted-" + CaRoWebutils.getTimeStamp() + "." + (req[1].equals("caro") ? "ro" : "omex"));
        try {
            Files.copy(out.toPath(), result, StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            notifications.add(new CaRoNotification(CaRoNotification.SERVERITY_ERROR,
                    "wasn't able to copy converted container to storage"));
        }
    }

    JSONArray errors = new JSONArray();
    JSONArray warnings = new JSONArray();
    JSONArray notes = new JSONArray();
    for (CaRoNotification note : notifications)
        if (note.getSeverity() == CaRoNotification.SERVERITY_ERROR)
            errors.add(note.getMessage());
        else if (note.getSeverity() == CaRoNotification.SERVERITY_WARN)
            warnings.add(note.getMessage());
        else if (note.getSeverity() == CaRoNotification.SERVERITY_NOTE)
            notes.add(note.getMessage());

    JSONObject json = new JSONObject();
    json.put("errors", errors);
    json.put("warnings", warnings);
    json.put("notifications", notes);

    if (result != null && Files.exists(result)) {
        json.put("checkout", result.getFileName().toString());
        if (request.getParameter("redirect") != null && request.getParameter("redirect").equals("checkout")) {
            response.sendRedirect("/checkout/" + result.getFileName().toString());
        }
    }

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    PrintWriter outWriter = response.getWriter();
    outWriter.print(json);
    out.delete();
}