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.skynetcomputing.skynetclient.persistence.PersistenceManager.java

/**
 * Reads task file and initiates new task. Wipes current task directory.
 * TaskInfo is saved to file, and from now on can be retrieved with
 * getCurrentTask()/*from  w ww. ja  v  a 2s .  c o m*/
 *
 * @param inputFile
 * @return
 * @throws IOException
 * @throws ClassNotFoundException
 * @throws ParseException
 */
public SrzTask saveTaskFile(File inputFile) throws IOException, ClassNotFoundException, ParseException {
    clearTask();
    SrzTask task = readTaskFile(inputFile);
    File outputFile = new File(rootDir + TASK_DIR + task.getID() + SrzTask.EXT);
    Files.copy(inputFile.toPath(), outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    return task;
}

From source file:de.elomagic.mag.MAG.java

private void run(String[] args) {
    Path configurationFile = Paths.get(System.getProperty("user.dir"), "conf", "configuration.properties");

    DefaultParser parser = new DefaultParser();
    try {// ww w  . j a v a 2 s  .c o m
        CommandLine commandLine = parser.parse(options, args);
        if (commandLine.hasOption(optionHelp.getOpt())) {
            printHelp();
        } else if (commandLine.hasOption(optionEncrypt.getOpt())) {
            if (commandLine.hasOption(optionConfig.getOpt())) {
                String file = commandLine.getOptionValue(optionConfig.getOpt());
                configurationFile = Paths.get(file);
            }
            encryptConfiguration(configurationFile);
        } else {
            boolean initCreateOfConfig = false;
            if (commandLine.hasOption(optionConfig.getOpt())) {
                String file = commandLine.getOptionValue(optionConfig.getOpt());
                configurationFile = Paths.get(file);

                LOGGER.info("Using configuration file \"" + file + "\".");
            } else if (Files.notExists(configurationFile)) {
                System.out.println("Creating default configuration file \"" + configurationFile + "\".");
                try (InputStream in = getClass().getResourceAsStream(Configuration.DEFAULT_PROPERTIES_FILE)) {
                    Files.createDirectories(configurationFile.getParent());
                    Files.copy(in, configurationFile, StandardCopyOption.REPLACE_EXISTING);
                }
                System.out
                        .println("Configure file \"" + configurationFile + "\" as your needs and start again.");
                initCreateOfConfig = true;
            }

            if (!initCreateOfConfig) {
                Configuration.loadConfiguration(configurationFile);
                System.out.println("Use ctrl + c to terminate MAG....");
                createCamelMain().run();
                System.out.println("MAG was terminated....");
            }
        }
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (ParseException e) {
        LOGGER.error("Parameter syntax error.", e);
        printHelp();
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }

}

From source file:com.googlecode.download.maven.plugin.internal.DownloadCache.java

public void install(String url, File outputFile, String md5, String sha1, String sha512) throws Exception {
    if (md5 == null) {
        md5 = SignatureUtils.computeSignatureAsString(outputFile, MessageDigest.getInstance("MD5"));
    }//from  w  ww.  ja va  2s  .c  o  m
    if (sha1 == null) {
        sha1 = SignatureUtils.computeSignatureAsString(outputFile, MessageDigest.getInstance("SHA1"));
    }
    if (sha512 == null) {
        sha512 = SignatureUtils.computeSignatureAsString(outputFile, MessageDigest.getInstance("SHA-512"));
    }
    CachedFileEntry entry = getEntry(url, md5, sha1, sha512);
    if (entry != null) {
        return; // entry already here
    }
    entry = new CachedFileEntry();
    entry.fileName = outputFile.getName() + '_' + DigestUtils.md5Hex(url);
    Files.copy(outputFile.toPath(), new File(this.basedir, entry.fileName).toPath(),
            StandardCopyOption.REPLACE_EXISTING);
    // update index
    loadIndex();
    this.index.put(url, entry);
    saveIndex();
}

From source file:org.cloudfoundry.dependency.in.InAction.java

private Mono<Void> writeVersion() {
    try (InputStream in = new ByteArrayInputStream(new VersionHolder(this.request.getVersion().getRef())
            .toRepositoryVersion().getBytes(Charset.defaultCharset()))) {
        Files.createDirectories(this.destination);
        Files.copy(in, getVersionFile(), StandardCopyOption.REPLACE_EXISTING);
        return Mono.empty();
    } catch (IOException e) {
        throw Exceptions.propagate(e);
    }/* www .  j  a  v  a  2  s . co m*/
}

From source file:org.eclipse.cdt.arduino.core.internal.board.ArduinoBoardManager.java

public ArduinoBoardManager() {
    new Job(Messages.ArduinoBoardManager_0) {
        protected IStatus run(IProgressMonitor monitor) {
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpGet get = new HttpGet("http://downloads.arduino.cc/packages/package_index.json"); //$NON-NLS-1$
                try (CloseableHttpResponse response = client.execute(get)) {
                    if (response.getStatusLine().getStatusCode() >= 400) {
                        return new Status(IStatus.ERROR, Activator.getId(),
                                response.getStatusLine().getReasonPhrase());
                    } else {
                        HttpEntity entity = response.getEntity();
                        if (entity == null) {
                            return new Status(IStatus.ERROR, Activator.getId(), Messages.ArduinoBoardManager_1);
                        }/*from w  w w . j a va2 s.co  m*/
                        Files.createDirectories(packageIndexPath.getParent());
                        Files.copy(entity.getContent(), packageIndexPath, StandardCopyOption.REPLACE_EXISTING);
                    }
                }
            } catch (IOException e) {
                return new Status(IStatus.ERROR, Activator.getId(), e.getLocalizedMessage(), e);
            }
            return Status.OK_STATUS;
        }
    }.schedule();
}

From source file:nl.uva.mlc.eurovoc.dataprocessor.DataSeperator.java

public void foldCreator(int k, String inDir, String outDir) {
    try {//from w  w  w.ja  v  a2 s  .  c  o  m
        File out = new File(outDir);
        FileUtils.forceMkdir(out);
        File in = new File(inDir);
        File[] inFiles = in.listFiles();
        int inNumFiles = inFiles.length;
        int numFilesPerFold = inNumFiles / k;
        for (int i = 0; i < k; i++) {
            File fold = new File(outDir + "/fold" + i + "/test");
            FileUtils.forceMkdir(fold);
            for (int j = i * numFilesPerFold; j < (i + 1) * numFilesPerFold; j++) {
                if (inFiles[j].getName().startsWith("jrc") && inFiles[j].getName().endsWith(".xml")) {
                    File f = new File(fold.getAbsoluteFile() + "/" + inFiles[j].getName());
                    Files.copy(inFiles[j].toPath(), f.toPath(), REPLACE_EXISTING);
                }
            }
            File foldTrain = new File(outDir + "/fold" + i + "/train");
            FileUtils.forceMkdir(foldTrain);
            for (int j = 0; j < inFiles.length; j++) {
                if (j < i * numFilesPerFold || j >= (i + 1) * numFilesPerFold) {
                    if (inFiles[j].getName().startsWith("jrc") && inFiles[j].getName().endsWith(".xml")) {
                        File f = new File(foldTrain.getAbsoluteFile() + "/" + inFiles[j].getName());
                        Files.copy(inFiles[j].toPath(), f.toPath(), REPLACE_EXISTING);
                    }
                }
            }

        }
    } catch (IOException ex) {
        log.error(ex);
    }
}

From source file:com.geewhiz.pacify.utils.FileUtils.java

private static void copyDirectoryRecursively(File source, File target) throws IOException {
    if (!target.exists()) {
        Files.copy(source.toPath(), target.toPath(), java.nio.file.StandardCopyOption.COPY_ATTRIBUTES);
    }//from  ww w  .  j  a v a 2s . com

    for (String child : source.list()) {
        copyDirectory(new File(source, child), new File(target, child));
    }
}

From source file:de.flashpixx.rrd_antlr4.engine.template.IBaseTemplate.java

/**
 * copies files from the directory of the template to the output directory
 *
 * @param p_templatefile file within the template directory
 * @param p_output output directory/*  w  ww .  ja  v  a2  s  .c  om*/
 * @throws IOException on IO error
 * @throws URISyntaxException on URL syntax error
 */
protected final void copy(final String p_templatefile, final Path p_output)
        throws IOException, URISyntaxException {
    final Path l_target = Paths.get(p_output.toString(), p_templatefile);
    Files.createDirectories(l_target.getParent());
    Files.copy(CCommon.resourceurl(MessageFormat.format("{0}{1}{2}{3}", "de/flashpixx/rrd_antlr4/template/",
            m_name, "/", p_templatefile)).openStream(), l_target, StandardCopyOption.REPLACE_EXISTING);
}

From source file:com.yahoo.parsec.gradle.utils.FileUtils.java

/**
 * Write resource to file./*  w ww.  j  a  va  2s .c  o  m*/
 *
 * @param inputStream input stream
 * @param outputFile  output file
 * @param overwrite   overwrite flag
 * @throws IOException IOException
 */
public void writeResourceToFile(final InputStream inputStream, String outputFile, boolean overwrite)
        throws IOException {
    File file = new File(outputFile);
    String outputFileDigest = "";

    if (file.exists()) {
        if (!overwrite) {
            logger.info("Skipping pre-existing " + outputFile);
            return;
        } else {
            try (InputStream outputFileStream = new FileInputStream(file)) {
                outputFileDigest = DigestUtils.md5Hex(outputFileStream);
            } catch (IOException e) {
                throw e;
            }
        }
    }

    try {
        byte[] bytes = IOUtils.toByteArray(inputStream);
        if (DigestUtils.md5Hex(bytes).equals(outputFileDigest)) {
            logger.info("Skipping unmodified " + outputFile);
            return;
        } else {
            logger.info("Creating file " + outputFile);
            Files.copy(new ByteArrayInputStream(bytes), Paths.get(outputFile),
                    StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (IOException e) {
        throw e;
    }
}

From source file:ml.dmlc.xgboost4j.java.NativeLibrary.java

private static File extract(String libPath, ClassLoader classLoader)
        throws IOException, IllegalArgumentException {

    // Split filename to prefix and suffix (extension)
    String filename = libPath.substring(libPath.lastIndexOf('/') + 1);
    int lastDotIdx = filename.lastIndexOf('.');
    String prefix = "";
    String suffix = null;//from   w ww  .j a  v  a2s  .  c  o m
    if (lastDotIdx >= 0 && lastDotIdx < filename.length() - 1) {
        prefix = filename.substring(0, lastDotIdx);
        suffix = filename.substring(lastDotIdx);
    }

    // Prepare temporary file
    File temp = File.createTempFile(prefix, suffix);
    temp.deleteOnExit();

    // Open and check input stream
    InputStream is = classLoader.getResourceAsStream(libPath);
    if (is == null) {
        throw new FileNotFoundException("File " + libPath + " was not found inside JAR.");
    }

    // Open output stream and copy data between source file in JAR and the temporary file
    try {
        Files.copy(is, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } finally {
        is.close();
    }

    return temp;
}