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:co.marcin.novaguilds.manager.ConfigManager.java

public void backupFile() throws IOException {
    File backupFile = new File(getConfigFile().getParentFile(), "config.yml.backup");
    Files.copy(getConfigFile().toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

From source file:facs.utils.Billing.java

/**
 * Helper method. copies files and directories from source to target source and target can be
 * created via the command: FileSystems.getDefault().getPath(String path, ... String more) or
 * Paths.get(String path, ... String more) Note: overrides existing folders
 * //w w w.java2s  .  com
 * @param source
 * @param target
 * @return true if copying was successful
 */
public boolean copy(final Path source, final Path target) {
    try {
        Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                new SimpleFileVisitor<Path>() {

                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        Path targetdir = target.resolve(source.relativize(dir));
                        try {
                            Files.copy(dir, targetdir, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
                        } catch (FileAlreadyExistsException e) {
                            if (!Files.isDirectory(targetdir)) {
                                throw e;
                            }
                        }

                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        Files.copy(file, target.resolve(source.relativize(file)));
                        return FileVisitResult.CONTINUE;

                    }

                });
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return false;
    }
    return true;
}

From source file:edu.utah.bmi.ibiomes.lite.IBIOMESLiteManager.java

/**
 * Publish experiment. Parse corresponding directory if descriptor files does not exist yet.
 * @param experimentDirPath Path to experiment directory
 * @param software Software context// w  w w  . j ava 2s  .  c  o  m
 * @param xmlDescPath Path to XML file containing metadata generation rules
 * @param depth 
 * @throws Exception 
 */
public void publishExperiment(String experimentDirPath, String software, String xmlDescPath,
        boolean isForceDescUpdate, int depth) throws Exception {
    Locker experimentLocker = null;
    Locker webdirLocker = null;
    try {
        //lock directory being parsed
        experimentLocker = new Locker(experimentDirPath);
        webdirLocker = new Locker(publicHtmlFolder);
        //check lock ... 
        boolean isLocked = experimentLocker.lock();
        if (isLocked) {
            File experimentDesc = new File(
                    experimentDirPath + PATH_FOLDER_SEPARATOR + IBIOMES_DESC_FILE_TREE_FILE_NAME);
            if (!experimentDesc.exists() || isForceDescUpdate) {
                //parse directory
                this.parse(experimentDirPath, software, xmlDescPath, depth);
            } else {
                if (outputToConsole)
                    System.out.println("Using existing descriptors (use -f option to force parsing)...");
            }
            //lock web directory for updates
            if (outputToConsole)
                System.out.println("Wating for other users to finish publishing...");
            isLocked = webdirLocker.waitAndLock();

            //update XML file representing experiment list
            XmlExperimentFile experimentXml = new XmlExperimentFile(experimentDesc.getAbsolutePath());
            int id = experimentListXml.addNewExperiment(experimentXml);
            experimentListXml.saveXml();

            //create new directory for this experiment
            String liteDirPath = publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_EXPERIMENT_DIR
                    + PATH_FOLDER_SEPARATOR + id;
            if (Files.exists(Paths.get(liteDirPath)))
                Utils.removeDirectoryRecursive(Paths.get(liteDirPath));
            Files.createDirectory(Paths.get(liteDirPath));

            //copy experiment XML descriptors
            String newFileTreeXmlPath = liteDirPath + "/index.xml";
            String newWorkflowXmlPath = liteDirPath + "/index-details.xml";
            Files.copy(Paths.get(experimentDesc.getAbsolutePath()), Paths.get(newFileTreeXmlPath),
                    StandardCopyOption.REPLACE_EXISTING);
            Files.copy(Paths.get(experimentDirPath + PATH_FOLDER_SEPARATOR + IBIOMES_DESC_WORKFLOW_FILE_NAME),
                    Paths.get(newWorkflowXmlPath), StandardCopyOption.REPLACE_EXISTING);

            //pull data files (csv, pdb, and images)
            String dataDirPath = liteDirPath + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_DATA_DIR;
            Files.createDirectory(Paths.get(dataDirPath));
            this.pullDataFilesForExperiment(newFileTreeXmlPath, newWorkflowXmlPath,
                    liteDirPath + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_DATA_DIR);

            //generate HTML pages
            if (outputToConsole)
                System.out.println("Generating HTML...");
            //experiment summary
            this.transformXmlToHtml(newWorkflowXmlPath,
                    publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_EXPERIMENT_DIR
                            + PATH_FOLDER_SEPARATOR + id + PATH_FOLDER_SEPARATOR + "index.html",
                    publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_EXPERIMENT_SUMMARY_XSL_PATH);
            //experiment workflow (tree view)
            this.transformXmlToHtml(newWorkflowXmlPath,
                    publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_EXPERIMENT_DIR
                            + PATH_FOLDER_SEPARATOR + id + PATH_FOLDER_SEPARATOR + "details.html",
                    publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_EXPERIMENT_WORKFLOW_XSL_PATH);
            //experiment runs (timings, resources)
            this.transformXmlToHtml(newWorkflowXmlPath,
                    publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_EXPERIMENT_DIR
                            + PATH_FOLDER_SEPARATOR + id + PATH_FOLDER_SEPARATOR + "runs.html",
                    publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_EXPERIMENT_RUNS_XSL_PATH);
            //experiment file browser
            this.transformXmlToHtml(newFileTreeXmlPath,
                    publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_EXPERIMENT_DIR
                            + PATH_FOLDER_SEPARATOR + id + PATH_FOLDER_SEPARATOR + "files.html",
                    publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_EXPERIMENT_FILE_TREE_XSL_PATH);
            //list of experiments
            experimentListXml.saveToHTML(publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_LITE_HTML_INDEX,
                    publicHtmlFolder + PATH_FOLDER_SEPARATOR + IBIOMES_EXPERIMENT_SET_XSL_PATH);
        } else {
            System.out.println("Could not lock " + experimentDirPath + " for parsing.");
            System.out.println(
                    "Another user might be publishing this experiment right now. If you believe this is not the case, delete the "
                            + Locker.LOCK_FILE_NAME + " file in the experiment directory and re-try.");
        }

        //unlock directories
        experimentLocker.unlock();
        webdirLocker.unlock();

    } catch (Exception e) {
        if (experimentLocker != null)
            experimentLocker.unlock();
        if (webdirLocker != null)
            webdirLocker.unlock();
        throw e;
    }
}

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

public static void addFileToZip(@Nonnull Path sourceStream, @Nonnull Path destZipFile, @Nonnull String destFile,
        CopyOption... copyOptions) {
    try (FileSystem zipFileSystem = createZipFileSystem(destZipFile, false)) {
        final Path root = zipFileSystem.getPath("/");
        Path destFilePath = root.resolve(destFile);
        Files.createDirectories(destFilePath.getParent());
        logger.debug("Copy {} to {}, destFile: {}", sourceStream, destFile, destFilePath);

        Files.copy(sourceStream, destFilePath, copyOptions);
    } catch (IOException e) {
        throw new RuntimeIOException("Exception adding file " + sourceStream + " to " + destZipFile, e);
    }/*  w w w  . j ava 2 s  .  c  o  m*/
}

From source file:de.elomagic.maven.http.HTTPMojo.java

/**
 * @todo Must may be refactored. Only a prototype
 * @param file//from w  w  w  .j  a  v  a2 s .  c o  m
 * @param destDirectory
 * @throws MojoExecutionException
 */
private void unzipToFile(final File file, final File destDirectory) throws Exception {
    getLog().info("Extracting downloaded file to folder \"" + destDirectory + "\".");

    int filesCount = 0;

    // create the destination directory structure (if needed)
    destDirectory.mkdirs();

    // open archive for reading
    try (ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ)) {
        // For every zip archive entry do
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry entry = zipFileEntries.nextElement();
            getLog().debug("Extracting entry: " + entry);

            //create destination file
            // TODO Check entry path on path injections
            File destFile = new File(destDirectory, entry.getName());

            //create parent directories if needed
            File parentDestFile = destFile.getParentFile();
            parentDestFile.mkdirs();

            if (!entry.isDirectory()) {
                BufferedInputStream bufIS = new BufferedInputStream(zipFile.getInputStream(entry));

                // write the current file to disk
                Files.copy(bufIS, destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                filesCount++;
            }
        }
    }

    getLog().info(filesCount + " files extracted.");
}

From source file:edu.harvard.iq.dataverse.ingest.IngestServiceBean.java

public List<DataFile> createDataFiles(DatasetVersion version, InputStream inputStream, String fileName,
        String suppliedContentType) throws IOException {
    List<DataFile> datafiles = new ArrayList<DataFile>();

    String warningMessage = null;

    // save the file, in the temporary location for now: 
    Path tempFile = null;//from w  w  w. j  ava2 s  .c  o m

    if (getFilesTempDirectory() != null) {
        tempFile = Files.createTempFile(Paths.get(getFilesTempDirectory()), "tmp", "upload");
        // "temporary" location is the key here; this is why we are not using 
        // the DataStore framework for this - the assumption is that 
        // temp files will always be stored on the local filesystem. 
        //          -- L.A. Jul. 2014
        logger.fine("Will attempt to save the file as: " + tempFile.toString());
        Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
    } else {
        throw new IOException("Temp directory is not configured.");
    }
    logger.fine("mime type supplied: " + suppliedContentType);
    // Let's try our own utilities (Jhove, etc.) to determine the file type 
    // of the uploaded file. (We may already have a mime type supplied for this
    // file - maybe the type that the browser recognized on upload; or, if 
    // it's a harvest, maybe the remote server has already given us the type
    // for this file... with our own type utility we may or may not do better 
    // than the type supplied:
    //  -- L.A. 
    String recognizedType = null;
    String finalType = null;
    try {
        recognizedType = FileUtil.determineFileType(tempFile.toFile(), fileName);
        logger.fine("File utility recognized the file as " + recognizedType);
        if (recognizedType != null && !recognizedType.equals("")) {
            // is it any better than the type that was supplied to us,
            // if any?
            // This is not as trivial a task as one might expect... 
            // We may need a list of "good" mime types, that should always
            // be chosen over other choices available. Maybe it should 
            // even be a weighed list... as in, "application/foo" should 
            // be chosen over "application/foo-with-bells-and-whistles".

            // For now the logic will be as follows: 
            //
            // 1. If the contentType supplied (by the browser, most likely) 
            // is some form of "unknown", we always discard it in favor of 
            // whatever our own utilities have determined; 
            // 2. We should NEVER trust the browser when it comes to the 
            // following "ingestable" types: Stata, SPSS, R;
            // 2a. We are willing to TRUST the browser when it comes to
            //  the CSV and XSLX ingestable types.
            // 3. We should ALWAYS trust our utilities when it comes to 
            // ingestable types. 

            if (suppliedContentType == null || suppliedContentType.equals("")
                    || suppliedContentType.equalsIgnoreCase(MIME_TYPE_UNDETERMINED_DEFAULT)
                    || suppliedContentType.equalsIgnoreCase(MIME_TYPE_UNDETERMINED_BINARY)
                    || (ingestableAsTabular(suppliedContentType)
                            && !suppliedContentType.equalsIgnoreCase(MIME_TYPE_CSV)
                            && !suppliedContentType.equalsIgnoreCase(MIME_TYPE_CSV_ALT)
                            && !suppliedContentType.equalsIgnoreCase(MIME_TYPE_XLSX))
                    || ingestableAsTabular(recognizedType) || recognizedType.equals("application/fits-gzipped")
                    || recognizedType.equalsIgnoreCase(ShapefileHandler.SHAPEFILE_FILE_TYPE)
                    || recognizedType.equals(MIME_TYPE_ZIP)) {
                finalType = recognizedType;
            }
        }

    } catch (Exception ex) {
        logger.warning("Failed to run the file utility mime type check on file " + fileName);
    }

    if (finalType == null) {
        finalType = (suppliedContentType == null || suppliedContentType.equals(""))
                ? MIME_TYPE_UNDETERMINED_DEFAULT
                : suppliedContentType;
    }

    // A few special cases: 

    // if this is a gzipped FITS file, we'll uncompress it, and ingest it as
    // a regular FITS file:

    if (finalType.equals("application/fits-gzipped")) {

        InputStream uncompressedIn = null;
        String finalFileName = fileName;
        // if the file name had the ".gz" extension, remove it, 
        // since we are going to uncompress it:
        if (fileName != null && fileName.matches(".*\\.gz$")) {
            finalFileName = fileName.replaceAll("\\.gz$", "");
        }

        DataFile datafile = null;
        try {
            uncompressedIn = new GZIPInputStream(new FileInputStream(tempFile.toFile()));
            datafile = createSingleDataFile(version, uncompressedIn, finalFileName,
                    MIME_TYPE_UNDETERMINED_DEFAULT);
        } catch (IOException ioex) {
            datafile = null;
        } finally {
            if (uncompressedIn != null) {
                try {
                    uncompressedIn.close();
                } catch (IOException e) {
                }
            }
        }

        // If we were able to produce an uncompressed file, we'll use it 
        // to create and return a final DataFile; if not, we're not going
        // to do anything - and then a new DataFile will be created further 
        // down, from the original, uncompressed file.
        if (datafile != null) {
            // remove the compressed temp file: 
            try {
                tempFile.toFile().delete();
            } catch (SecurityException ex) {
                // (this is very non-fatal)
                logger.warning("Failed to delete temporary file " + tempFile.toString());
            }

            datafiles.add(datafile);
            return datafiles;
        }

        // If it's a ZIP file, we are going to unpack it and create multiple 
        // DataFile objects from its contents:
    } else if (finalType.equals("application/zip")) {

        ZipInputStream unZippedIn = null;
        ZipEntry zipEntry = null;

        int fileNumberLimit = systemConfig.getZipUploadFilesLimit();

        try {
            Charset charset = null;
            /*
            TODO: (?)
            We may want to investigate somehow letting the user specify 
            the charset for the filenames in the zip file...
            - otherwise, ZipInputStream bails out if it encounteres a file 
            name that's not valid in the current charest (i.e., UTF-8, in 
            our case). It would be a bit trickier than what we're doing for 
            SPSS tabular ingests - with the lang. encoding pulldown menu - 
            because this encoding needs to be specified *before* we upload and
            attempt to unzip the file. 
                -- L.A. 4.0 beta12
            logger.info("default charset is "+Charset.defaultCharset().name());
            if (Charset.isSupported("US-ASCII")) {
            logger.info("charset US-ASCII is supported.");
            charset = Charset.forName("US-ASCII");
            if (charset != null) {
                logger.info("was able to obtain charset for US-ASCII");
            }
                    
            }
            */

            if (charset != null) {
                unZippedIn = new ZipInputStream(new FileInputStream(tempFile.toFile()), charset);
            } else {
                unZippedIn = new ZipInputStream(new FileInputStream(tempFile.toFile()));
            }

            while (true) {
                try {
                    zipEntry = unZippedIn.getNextEntry();
                } catch (IllegalArgumentException iaex) {
                    // Note: 
                    // ZipInputStream documentation doesn't even mention that 
                    // getNextEntry() throws an IllegalArgumentException!
                    // but that's what happens if the file name of the next
                    // entry is not valid in the current CharSet. 
                    //      -- L.A.
                    warningMessage = "Failed to unpack Zip file. (Unknown Character Set used in a file name?) Saving the file as is.";
                    logger.warning(warningMessage);
                    throw new IOException();
                }

                if (zipEntry == null) {
                    break;
                }
                // Note that some zip entries may be directories - we 
                // simply skip them:

                if (!zipEntry.isDirectory()) {
                    if (datafiles.size() > fileNumberLimit) {
                        logger.warning("Zip upload - too many files.");
                        warningMessage = "The number of files in the zip archive is over the limit ("
                                + fileNumberLimit
                                + "); please upload a zip archive with fewer files, if you want them to be ingested "
                                + "as individual DataFiles.";
                        throw new IOException();
                    }

                    String fileEntryName = zipEntry.getName();
                    logger.fine("ZipEntry, file: " + fileEntryName);

                    if (fileEntryName != null && !fileEntryName.equals("")) {

                        String shortName = fileEntryName.replaceFirst("^.*[\\/]", "");

                        // Check if it's a "fake" file - a zip archive entry 
                        // created for a MacOS X filesystem element: (these 
                        // start with "._")
                        if (!shortName.startsWith("._") && !shortName.startsWith(".DS_Store")
                                && !"".equals(shortName)) {
                            // OK, this seems like an OK file entry - we'll try 
                            // to read it and create a DataFile with it:

                            DataFile datafile = createSingleDataFile(version, unZippedIn, shortName,
                                    MIME_TYPE_UNDETERMINED_DEFAULT, false);

                            if (!fileEntryName.equals(shortName)) {
                                String categoryName = fileEntryName.replaceFirst("[\\/][^\\/]*$", "");
                                if (!"".equals(categoryName)) {
                                    logger.fine("setting category to " + categoryName);
                                    //datafile.getFileMetadata().setCategory(categoryName.replaceAll("[\\/]", "-"));
                                    datafile.getFileMetadata()
                                            .addCategoryByName(categoryName.replaceAll("[\\/]", "-"));
                                }
                            }

                            if (datafile != null) {
                                // We have created this datafile with the mime type "unknown";
                                // Now that we have it saved in a temporary location, 
                                // let's try and determine its real type:

                                String tempFileName = getFilesTempDirectory() + "/"
                                        + datafile.getStorageIdentifier();

                                try {
                                    recognizedType = FileUtil.determineFileType(new File(tempFileName),
                                            shortName);
                                    logger.fine("File utility recognized unzipped file as " + recognizedType);
                                    if (recognizedType != null && !recognizedType.equals("")) {
                                        datafile.setContentType(recognizedType);
                                    }
                                } catch (Exception ex) {
                                    logger.warning("Failed to run the file utility mime type check on file "
                                            + fileName);
                                }

                                datafiles.add(datafile);
                            }
                        }
                    }
                }
                unZippedIn.closeEntry();

            }

        } catch (IOException ioex) {
            // just clear the datafiles list and let 
            // ingest default to creating a single DataFile out
            // of the unzipped file. 
            logger.warning("Unzipping failed; rolling back to saving the file as is.");
            if (warningMessage == null) {
                warningMessage = "Failed to unzip the file. Saving the file as is.";
            }

            datafiles.clear();
        } finally {
            if (unZippedIn != null) {
                try {
                    unZippedIn.close();
                } catch (Exception zEx) {
                }
            }
        }
        if (datafiles.size() > 0) {
            // link the data files to the dataset/version: 
            Iterator<DataFile> itf = datafiles.iterator();
            while (itf.hasNext()) {
                DataFile datafile = itf.next();
                datafile.setOwner(version.getDataset());
                if (version.getFileMetadatas() == null) {
                    version.setFileMetadatas(new ArrayList());
                }
                version.getFileMetadatas().add(datafile.getFileMetadata());
                datafile.getFileMetadata().setDatasetVersion(version);

                /* TODO!!
                // re-implement this in some way that does not use the 
                // deprecated .getCategory() on FileMeatadata:
                if (datafile.getFileMetadata().getCategory() != null) {
                datafile.getFileMetadata().addCategoryByName(datafile.getFileMetadata().getCategory());
                datafile.getFileMetadata().setCategory(null);
                -- done? see above?
                }
                */
                version.getDataset().getFiles().add(datafile);
            }
            // remove the uploaded zip file: 
            try {
                Files.delete(tempFile);
            } catch (IOException ioex) {
                // do nothing - it's just a temp file.
                logger.warning("Could not remove temp file " + tempFile.getFileName().toString());
            }
            // and return:
            return datafiles;
        }

    } else if (finalType.equalsIgnoreCase(ShapefileHandler.SHAPEFILE_FILE_TYPE)) {
        // Shape files may have to be split into multiple files, 
        // one zip archive per each complete set of shape files:

        //File rezipFolder = new File(this.getFilesTempDirectory());
        File rezipFolder = this.getShapefileUnzipTempDirectory();

        IngestServiceShapefileHelper shpIngestHelper;
        shpIngestHelper = new IngestServiceShapefileHelper(tempFile.toFile(), rezipFolder);

        boolean didProcessWork = shpIngestHelper.processFile();
        if (!(didProcessWork)) {
            logger.severe("Processing of zipped shapefile failed.");
            return null;
        }
        for (File finalFile : shpIngestHelper.getFinalRezippedFiles()) {
            FileInputStream finalFileInputStream = new FileInputStream(finalFile);
            finalType = this.getContentType(finalFile);
            if (finalType == null) {
                logger.warning("Content type is null; but should default to 'MIME_TYPE_UNDETERMINED_DEFAULT'");
                continue;
            }
            DataFile new_datafile = createSingleDataFile(version, finalFileInputStream, finalFile.getName(),
                    finalType);
            if (new_datafile != null) {
                datafiles.add(new_datafile);
            } else {
                logger.severe("Could not add part of rezipped shapefile. new_datafile was null: "
                        + finalFile.getName());
            }
            finalFileInputStream.close();

        }

        // Delete the temp directory used for unzipping
        /*
        logger.fine("Delete temp shapefile unzip directory: " + rezipFolder.getAbsolutePath());
        FileUtils.deleteDirectory(rezipFolder);
                
        // Delete rezipped files
        for (File finalFile : shpIngestHelper.getFinalRezippedFiles()){
        if (finalFile.isFile()){
            finalFile.delete();
        }
        }
        */

        if (datafiles.size() > 0) {
            return datafiles;
        } else {
            logger.severe("No files added from directory of rezipped shapefiles");
        }
        return null;

    }

    // Finally, if none of the special cases above were applicable (or 
    // if we were unable to unpack an uploaded file, etc.), we'll just 
    // create and return a single DataFile:
    // (Note that we are passing null for the InputStream; that's because
    // we already have the file saved; we'll just need to rename it, below)

    DataFile datafile = createSingleDataFile(version, null, fileName, finalType);

    if (datafile != null) {
        fileService.generateStorageIdentifier(datafile);
        if (!tempFile.toFile()
                .renameTo(new File(getFilesTempDirectory() + "/" + datafile.getStorageIdentifier()))) {
            return null;
        }

        // MD5:
        MD5Checksum md5Checksum = new MD5Checksum();
        try {
            datafile.setmd5(
                    md5Checksum.CalculateMD5(getFilesTempDirectory() + "/" + datafile.getStorageIdentifier()));
        } catch (Exception md5ex) {
            logger.warning("Could not calculate MD5 signature for new file " + fileName);
        }

        if (warningMessage != null) {
            createIngestFailureReport(datafile, warningMessage);
            datafile.SetIngestProblem();
        }
        datafiles.add(datafile);

        return datafiles;
    }

    return null;
}

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

public static void addFileToZip(@Nonnull InputStream sourceFile, @Nonnull Path destZipFile,
        @Nonnull String destFile, CopyOption... copyOptions) {
    try (FileSystem zipFileSystem = createZipFileSystem(destZipFile, false)) {
        final Path root = zipFileSystem.getPath("/");
        Path destFilePath = root.resolve(destFile);
        Files.createDirectories(destFilePath.getParent());
        logger.debug("Copy {} to {}, destFile: {}", sourceFile, destFile, destFilePath);

        Files.copy(sourceFile, destFilePath, copyOptions);
    } catch (IOException e) {
        throw new RuntimeIOException("Exception adding file " + sourceFile + " to " + destZipFile, e);
    }/*from   www  .j a  v a2s  .  c  o m*/
}

From source file:dotaSoundEditor.Controls.ItemPanel.java

@Override
protected File promptUserForNewFile(String wavePath) {
    DefaultMutableTreeNode selectedTreeNode = (DefaultMutableTreeNode) getTreeNodeFromWavePath(wavePath);
    String waveString = selectedTreeNode.getUserObject().toString();
    String allowedExtension = FilenameUtils.getExtension(waveString).replace("\"", "");

    JFileChooser chooser = new JFileChooser(new File(UserPrefs.getInstance().getWorkingDirectory()));
    FileNameExtensionFilter filter = allowedExtension.equals("wav") ? new FileNameExtensionFilter("WAVs", "wav")
            : new FileNameExtensionFilter("MP3s", "mp3");
    chooser.setAcceptAllFileFilterUsed((false));
    chooser.setFileFilter(filter);//from   ww  w .j a v  a2  s  .  c  o m
    chooser.setMultiSelectionEnabled(false);

    int chooserRetVal = chooser.showOpenDialog(chooser);
    if (chooserRetVal == JFileChooser.APPROVE_OPTION) {
        Path chosenFile = Paths.get(chooser.getSelectedFile().getAbsolutePath());

        int startIndex = -1;
        int endIndex = -1;
        //Get the actual value for the wavestring key-value pair.
        if (waveString.contains("\"wave\"")) {
            startIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 2);
            endIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 3);
        } else //Some wavestrings don't have the "wave" at the beginning for some reason
        {
            startIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 0);
            endIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 1);
        }
        String waveStringFilePath = waveString.substring(startIndex, endIndex + 1);
        String waveStringNormalizedFilePath = waveStringFilePath.substring(0,
                waveStringFilePath.lastIndexOf("\""));
        waveStringNormalizedFilePath = waveStringNormalizedFilePath.replace(")", "");
        waveStringNormalizedFilePath = waveStringNormalizedFilePath.replace("\"", "");

        Path destPath = Paths.get(installDir, "/dota/sound/" + waveStringNormalizedFilePath);
        UserPrefs.getInstance().setWorkingDirectory(chosenFile.getParent().toString());

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

            if (waveString.contains("//")) {
                waveString = waveString
                        .replace(waveString.substring(waveString.indexOf("//"), waveString.length()), "");
            }
            waveString = waveString.replace(waveStringFilePath, "\"" + waveStringNormalizedFilePath
                    + "\" //Replaced by: " + chosenFile.getFileName().toString());
            selectedTreeNode.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.netflix.spinnaker.halyard.config.model.v1.node.Node.java

public List<String> backupLocalFiles(String outputPath) {
    List<String> files = new ArrayList<>();

    Consumer<Node> fileFinder = n -> files.addAll(n.localFiles().stream().map(f -> {
        try {//from   w  w w . j av  a  2s . c  om
            f.setAccessible(true);
            String fPath = (String) f.get(n);
            if (fPath == null) {
                try {
                    fPath = (String) n.getClass().getMethod("get" + StringUtils.capitalize(f.getName()))
                            .invoke(n);
                } catch (NoSuchMethodException | InvocationTargetException ignored) {
                }
            }

            if (fPath == null) {
                return null;
            }

            File fFile = new File(fPath);
            String fName = fFile.getName();

            // Hash the path to uniquely flatten all files into the output directory
            Path newName = Paths.get(outputPath, Math.abs(fPath.hashCode()) + "-" + fName);
            File parent = newName.toFile().getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            } else if (fFile.getParent().equals(parent.toString())) {
                // Don't move paths that are already in the right folder
                return fPath;
            }
            Files.copy(Paths.get(fPath), newName, REPLACE_EXISTING);

            f.set(n, newName.toString());
            return newName.toString();
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Failed to get local files for node " + n.getNodeName(), e);
        } catch (IOException e) {
            throw new HalException(FATAL, "Failed to backup user file: " + e.getMessage(), e);
        } finally {
            f.setAccessible(false);
        }
    }).filter(Objects::nonNull).collect(Collectors.toList()));
    recursiveConsume(fileFinder);

    return files;
}