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:com.ecofactor.qa.automation.platform.ops.impl.AbstractDriverOperations.java

/**
 * Take screen shot./*from  w  ww .  j  a va2  s. c  om*/
 * @param fileNames the file names
 * @throws DeviceException the device exception
 * @see com.ecofactor.qa.automation.mobile.ops.DriverOperations#takeScreenShot(java.lang.String[])
 */
@Override
public void takeScreenShot(final String... fileNames) throws DeviceException {

    try {
        final Path screenshot = ((TakesScreenshot) getDeviceDriver()).getScreenshotAs(OutputType.FILE).toPath();
        final Path screenShotFile = getTargetScreenshotPath(fileNames);
        Files.copy(screenshot, screenShotFile, StandardCopyOption.REPLACE_EXISTING);
        if (Files.exists(screenShotFile)) {
            LOGGER.info("Saved screenshot for " + fileNames + AT_STRING + screenShotFile);
        } else {
            LOGGER.info("Unable to save screenshot for " + fileNames + AT_STRING + screenShotFile);
        }
    } catch (WebDriverException | IOException e) {
        LOGGER.error("Error taking screenshot for " + fileNames, e);
    }
}

From source file:onl.area51.filesystem.ftp.client.FTPClient.java

/**
 * Retrieve a remote file/*from  w w w .  j a  v a  2s .  c om*/
 * <p>
 * @param remote  file name
 * @param target  file to create. Name will also be the remote name in the current directory
 * @param options CopyOptions to use
 * <p>
 * @throws IOException
 */
default void retrieve(String remote, Path target, CopyOption... options) throws IOException {
    try (InputStream is = retrieveFileStream(remote)) {
        if (is == null) {
            throw new FileNotFoundException(target.toString());
        }
        Files.copy(is, target, options);
    } finally {
        completePendingCommand();
    }
}

From source file:com.vasquez.FileSwitcher.java

private void restoreFiles() {
    Logger.LogInfo("Restoring important Diablo II files...");

    for (String file : requiredFiles) {
        File sourceFile = null;// w w  w .j  av  a2s .  c om
        File targetFile = new File(root.getAbsolutePath() + "\\" + file);

        // Sets the path depending if it's an expansion or classic entry
        if (expansion) {
            sourceFile = new File(root.getAbsolutePath() + "\\Expansion\\" + version + "\\" + file);
        } else {
            sourceFile = new File(root.getAbsolutePath() + "\\Classic\\" + version + "\\" + file);
        }

        Path sourceDll = Paths.get(sourceFile.getAbsolutePath());
        Path destDll = Paths.get(targetFile.getAbsolutePath());

        if (sourceFile.exists()) {
            try {
                Files.copy(sourceDll, destDll, REPLACE_EXISTING);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // Restore the 'data' directory if it exists
    doDataDir(1);

    // Switch the Expansion MPQs to different locations depending if expansion/classic
    if (expansion) {
        switchTo(GameType.Expansion);
    } else {
        switchTo(GameType.Classic);
    }
}

From source file:com.cyc.corpus.nlmpaper.AIMedOpenAccessPaper.java

private Optional<Path> getZipArchive(boolean cached) {
    try {/*from   w  w  w  .ja  v a2  s . co m*/
        Path cachedFilePath = cachedArchivePath();
        Path parentDirectoryPath = cachedFilePath.getParent();

        // create the parent directory it doesn't already exist
        if (Files.notExists(parentDirectoryPath, LinkOption.NOFOLLOW_LINKS)) {
            Files.createDirectory(parentDirectoryPath);
        }

        // if cached file already exist - return it, no download necessary
        if (cached && Files.exists(cachedFilePath, LinkOption.NOFOLLOW_LINKS)) {
            return Optional.of(cachedFilePath.toAbsolutePath());
        }

        // otherwise, download the file
        URL url = new URL(PROTEINS_URL);
        Files.copy(url.openStream(), cachedFilePath, StandardCopyOption.REPLACE_EXISTING);
        return Optional.of(cachedFilePath.toAbsolutePath());

    } catch (MalformedURLException ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    }

    return Optional.empty();
}

From source file:eu.itesla_project.sampling.tools.DataComparatorTool.java

@Override
public void run(CommandLine line) throws Exception {
    try (ComputationManager computationManager = new LocalComputationManager()) {
        SamplerWp41Config config = SamplerWp41Config.load();

        //String dataDir = line.getOptionValue(DataComparatorCommand.DATA_DIR);
        String dataDir = config.getValidationDir().toFile().getAbsolutePath();
        if (!Files.exists(config.getValidationDir())) {
            throw new RuntimeException("validation data directory not found:  " + config.getValidationDir());
        }//www  .j  ava 2s . c o m

        String oFilePrefix = line.getOptionValue("ofile");
        String set1 = line.hasOption("set1") ? line.getOptionValue("set1") : "";
        String set2 = line.hasOption("set2") ? line.getOptionValue("set2") : "";

        if ((!"".equals(set1 + set2)) && (("".equals(set1)) || ("".equals(set2)))) {
            throw new RuntimeException("either specify both set1 and set2 parameters, or none of them");
        }

        try (CommandExecutor executor = computationManager.newCommandExecutor(createEnv(config),
                WORKING_DIR_PREFIX, config.isDebug())) {
            Path workingDir = executor.getWorkingDir();
            eu.itesla_project.computation.Command cmd = createConcatMatFilesCmd(config.getValidationDir(),
                    MOD3FILES_PATTERN, config.getValidationDir().resolve(CONCATSAMPLESFILENAME), config);
            int priority = 1;
            ExecutionReport report = executor.start(new CommandExecution(cmd, 1, priority));
            report.log();
            if (report.getErrors().isEmpty()) {
                report = executor.start(new CommandExecution(createDataComparatorCmd(
                        config.getValidationDir().resolve(M1INPUTFILENAME).toFile().getAbsolutePath(),
                        config.getValidationDir().resolve(CONCATSAMPLESFILENAME).toFile().getAbsolutePath(),
                        set1, set2, config), 1, priority));
                report.log();
                Files.copy(workingDir.resolve(DATA_COMPARATOR_OUT_FIG), Paths.get(oFilePrefix + ".fig"),
                        REPLACE_EXISTING);
                Files.copy(workingDir.resolve(DATA_COMPARATOR_OUT_PNG), Paths.get(oFilePrefix + ".png"),
                        REPLACE_EXISTING);
            }
        }
    }
}

From source file:org.transitime.gtfs.GtfsUpdatedModule.java

/**
 * Copies the specified file to a directory at the same directory level but
 * with the directory name that is the last modified date of the file (e.g.
 * 03-28-2015).//from w ww.  ja v a 2  s .c o m
 * 
 * @param fullFileName
 *            The full name of the file to be copied
 */
private static void archive(String fullFileName) {
    // Determine name of directory to archive file into. Use date of
    // lastModified time of file e.g. MM-dd-yyyy.
    File file = new File(fullFileName);
    Date lastModified = new Date(file.lastModified());
    String dirName = Time.dateStr(lastModified);

    // Copy the file to the sibling directory with the name that is the
    // last modified date (e.g. 03-28-2015)
    Path source = Paths.get(fullFileName);
    Path target = source.getParent().getParent().resolve(dirName).resolve(source.getFileName());

    logger.info("Archiving file {} to {}", source.toString(), target.toString());

    try {
        // Create the directory where file is to go
        String fullDirName = target.getParent().toString();
        new File(fullDirName).mkdir();

        // Copy the file to the directory
        Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES);
    } catch (IOException e) {
        logger.error("Was not able to archive GTFS file {} to {}", source.toString(), target);
    }
}

From source file:com.github.thorqin.webapi.FileManager.java

public void copyTo(String fileId, File destPath, boolean replaceExisting) throws IOException {
    File dataFile = new File(uploadDir + "/" + fileId + ".data");
    if (replaceExisting)
        Files.copy(dataFile.toPath(), destPath.toPath(), StandardCopyOption.REPLACE_EXISTING);
    else/*from   www  .  j a va2 s  . co  m*/
        Files.copy(dataFile.toPath(), destPath.toPath());
}

From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java

private static boolean generateAppfromXML(String fn) {

    long starttime = System.currentTimeMillis();

    // fn must not be null or empty
    if (fn == null || fn.isEmpty()) {
        log.error("Empty filename!");
        return false;
    }//w w w  .  ja v  a2 s . c o  m
    // fn must be a valid file and readable
    File runnableitem = new File(fn);
    if (!runnableitem.exists() || !runnableitem.canRead()) {
        log.error("{} doesn't exists or can't be read! ", fn);
        return false;
    }
    // load as xml file, validate it, and ...
    Document doc;
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        //dbf.setValidating(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        doc = db.parse(runnableitem);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        log.error("{} occured: {}", e.getClass().getSimpleName(), e.getLocalizedMessage());
        return false;
    }
    // extract project id, name  and version from it.
    String projectid = doc.getDocumentElement().getAttribute("id");
    if ((projectid == null) || projectid.isEmpty()) {
        log.error("Missing project id in description file!");
        return false;
    }
    String projectname;
    try {
        projectname = doc.getElementsByTagNameNS("bibiserv:de.unibi.techfak.bibiserv.cms", "name").item(0)
                .getTextContent();
    } catch (NullPointerException e) {
        log.error("Missing project name in description file!");
        return false;
    }

    String projectversion = "unknown";
    try {
        projectversion = doc.getElementsByTagNameNS("bibiserv:de.unibi.techfak.bibiserv.cms", "version").item(0)
                .getTextContent();
    } catch (NullPointerException e) {
        log.warn("Missing project version in description file!");

    }

    File projectdir = new File(
            config.getProperty("project.dir", config.getProperty("target.dir") + "/" + projectid));

    mkdirs(projectdir + "/src/main/java");
    mkdirs(projectdir + "/src/main/config");
    mkdirs(projectdir + "/src/main/libs");
    mkdirs(projectdir + "/src/main/pages");
    mkdirs(projectdir + "/src/main/resources");
    mkdirs(projectdir + "/src/main/downloads");

    // place runnableitem in config dir
    try {
        Files.copy(runnableitem.toPath(), new File(projectdir + "/src/main/config/runnableitem.xml").toPath(),
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        log.error("{} occurred : {}", e.getClass().getSimpleName(), e.getLocalizedMessage());
        return false;
    }

    // copy files from SKELETON to projectdir and replace wildcard expression
    String[] SKELETON_INPUT_ARRAY = { "/pom.xml", "/src/main/config/log4j-tool.properties" };
    String SKELETON_INPUT = null;
    try {
        for (int c = 0; c < SKELETON_INPUT_ARRAY.length; c++) {
            SKELETON_INPUT = SKELETON_INPUT_ARRAY[c];

            InputStream in = Main.class.getResourceAsStream("/SKELETON" + SKELETON_INPUT);
            if (in == null) {
                throw new IOException();
            }

            CopyAndReplace(in, new FileOutputStream(new File(projectdir, SKELETON_INPUT)), projectid,
                    projectname, projectversion);
        }

    } catch (IOException e) {
        log.error("Exception occurred while calling 'copyAndReplace(/SKELETON{},{}/{},{},{},{})'",
                SKELETON_INPUT, projectdir, SKELETON_INPUT, projectid, projectname, projectversion);
        return false;
    }

    log.info("Empty project created! ");

    try {
        // _base 

        generate(CodeGen_Implementation.class, runnableitem, projectdir);
        log.info("Implementation generated!");

        generate(CodeGen_Implementation_Threadworker.class, runnableitem, projectdir);
        log.info("Implementation_Threadworker generated!");

        generate(CodeGen_Utilities.class, runnableitem, projectdir);
        log.info("Utilities generated!");

        generate(CodeGen_Common.class, runnableitem, projectdir, "/templates/common", RESOURCETYPE.isDirectory);

        log.info("Common generated!");

        // _REST
        generate(CodeGen_REST.class, runnableitem, projectdir);
        generate(CodeGen_REST_general.class, runnableitem, projectdir);

        log.info("REST generated!");

        //_HTML
        generate(CodeGen_WebSubmissionPage.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Input.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Param.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Result.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Visualization.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Formatchooser.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionPage_Resulthandler.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Function.class, runnableitem, projectdir);
        generate(CodeGen_Session_Reset.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Controller.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Input.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Param.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Result.class, runnableitem, projectdir);
        generate(CodeGen_WebSubmissionBean_Resulthandler.class, runnableitem, projectdir);
        generate(CodeGen_Webstart.class, runnableitem, projectdir); // can be removed ???
        generate(CodeGen_WebToolBeanContextConfig.class, runnableitem, projectdir);
        generate(CodeGen_WebManual.class, runnableitem, projectdir);
        generate(CodeGen_WebPage.class, runnableitem, projectdir, "/templates/pages", RESOURCETYPE.isDirectory);

        log.info("XHTML pages generated!");

        long time = (System.currentTimeMillis() - starttime) / 1000;

        log.info("Project \"{}\" (id:{}, version:{}) created at '{}' in {} seconds.", projectname, projectid,
                projectversion, projectdir, time);

    } catch (CodeGenParserException e) {
        log.error("CodeGenParserException occurred :", e);
        return false;
    }
    return true;
}

From source file:com.skynetcomputing.skynetclient.persistence.PersistenceManager.java

/**
 * Saves jar file to file system. Name is its MD5 checksum
 *
 * @param jarFile//w  w w  .j a va2 s  .  com
 * @return
 * @throws IOException
 */
public File saveJar(File jarFile) throws IOException {
    File outputFile = null;
    try (FileInputStream fis = new FileInputStream(jarFile)) {
        String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);
        outputFile = new File(String.format("%s%s%s%s", rootDir, JAR_DIR, md5, SrzJar.EXT));
        Files.copy(jarFile.toPath(), outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }
    return outputFile;
}

From source file:com.sonar.it.scanner.msbuild.TestUtils.java

private static void replaceInZip(URI zipUri, Path src, String dest) {
    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    // locate file system by using the syntax
    // defined in java.net.JarURLConnection
    URI uri = URI.create("jar:" + zipUri);
    try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
        Path pathInZipfile = zipfs.getPath(dest);
        LOG.info("Replacing the file " + pathInZipfile + " in the zip " + zipUri + " with " + src);
        Files.copy(src, pathInZipfile, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }/*from w  w  w  . j  a  va2s .  c om*/
}