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:Main.java

public static void main(String[] args) {
    Path copy_from_2 = Paths.get("C:/tutorial/Java/JavaFX", "tutor.txt");
    Path copy_to_2 = Paths.get("C:/tutorial/Java/Swing", "tutor.txt");

    try (InputStream is = new FileInputStream(copy_from_2.toFile())) {

        Files.copy(is, copy_to_2, REPLACE_EXISTING);

    } catch (IOException e) {
        System.err.println(e);/*from ww  w.ja  v  a  2  s  .com*/
    }

}

From source file:de.jackwhite20.japs.server.Main.java

public static void main(String[] args) throws Exception {

    Config config = null;/*www  . j  a  v a  2s.  c o m*/

    if (args.length > 0) {
        Options options = new Options();
        options.addOption("h", true, "Address to bind to");
        options.addOption("p", true, "Port to bind to");
        options.addOption("b", true, "The backlog");
        options.addOption("t", true, "Worker thread count");
        options.addOption("d", false, "If debug is enabled or not");
        options.addOption("c", true, "Add server as a cluster");
        options.addOption("ci", true, "Sets the cache check interval");
        options.addOption("si", true, "Sets the snapshot interval");

        CommandLineParser commandLineParser = new BasicParser();
        CommandLine commandLine = commandLineParser.parse(options, args);

        if (commandLine.hasOption("h") && commandLine.hasOption("p") && commandLine.hasOption("b")
                && commandLine.hasOption("t")) {

            List<ClusterServer> clusterServers = new ArrayList<>();

            if (commandLine.hasOption("c")) {
                for (String c : commandLine.getOptionValues("c")) {
                    String[] splitted = c.split(":");
                    clusterServers.add(new ClusterServer(splitted[0], Integer.parseInt(splitted[1])));
                }
            }

            config = new Config(commandLine.getOptionValue("h"),
                    Integer.parseInt(commandLine.getOptionValue("p")),
                    Integer.parseInt(commandLine.getOptionValue("b")), commandLine.hasOption("d"),
                    Integer.parseInt(commandLine.getOptionValue("t")), clusterServers,
                    (commandLine.hasOption("ci")) ? Integer.parseInt(commandLine.getOptionValue("ci")) : 300,
                    (commandLine.hasOption("si")) ? Integer.parseInt(commandLine.getOptionValue("si")) : -1);
        } else {
            System.out.println(
                    "Usage: java -jar japs-server.jar -h <Host> -p <Port> -b <Backlog> -t <Threads> [-c IP:Port IP:Port] [-d]");
            System.out.println(
                    "Example (with debugging enabled): java -jar japs-server.jar -h localhost -p 1337 -b 100 -t 4 -d");
            System.out.println(
                    "Example (with debugging enabled and cluster setup): java -jar japs-server.jar -h localhost -p 1337 -b 100 -t 4 -c localhost:1338 -d");
            System.exit(-1);
        }
    } else {
        File configFile = new File("config.json");
        if (!configFile.exists()) {
            try {
                Files.copy(JaPS.class.getClassLoader().getResourceAsStream("config.json"), configFile.toPath(),
                        StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                System.err.println("Unable to load default config!");
                System.exit(-1);
            }
        }

        try {
            config = new Gson().fromJson(
                    Files.lines(configFile.toPath()).map(String::toString).collect(Collectors.joining(" ")),
                    Config.class);
        } catch (IOException e) {
            System.err.println("Unable to load 'config.json' in current directory!");
            System.exit(-1);
        }
    }

    if (config == null) {
        System.err.println("Failed to create a Config!");
        System.err.println("Please check the program parameters or the 'config.json' file!");
    } else {
        System.err.println("Using Config: " + config);

        JaPS jaPS = new JaPS(config);
        jaPS.init();
        jaPS.start();
        jaPS.stop();
    }
}

From source file:com.ignorelist.kassandra.steam.scraper.TaggerCli.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException/* w  ww .j a  va2s  . com*/
 * @throws org.antlr.runtime.RecognitionException
 * @throws org.apache.commons.cli.ParseException
 */
public static void main(String[] args) throws IOException, RecognitionException, ParseException {
    Options options = buildOptions();
    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine;
    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.out.println(pe.getMessage());
        System.out.println();
        printHelp(options);
        System.exit(0);
        return;
    }
    if (commandLine.hasOption("h")) {
        printHelp(options);
        System.exit(0);
    }
    final PathResolver pathResolver = new PathResolver();

    Configuration configuration;
    Path configurationFile = pathResolver.findConfiguration();
    if (Files.isRegularFile(configurationFile)) {
        configuration = Configuration.fromPropertiesFile(configurationFile);
    } else {
        configuration = new Configuration();
    }
    configuration = toConfiguration(configuration, commandLine);
    //configuration.toProperties().store(System.err, null);

    if (!Files.isRegularFile(configurationFile)) {
        configuration.writeProperties(configurationFile);
        System.err.println(
                "no configuration file present, write based on CLI options: " + configurationFile.toString());
        configuration.toProperties().store(System.err, null);
    }

    Set<Path> sharedConfigPaths = configuration.getSharedConfigPaths();
    if (sharedConfigPaths.size() > 1 && !commandLine.hasOption("w")) {
        System.err.println("multiple sharedconfig.vdf available:\n" + Joiner.on("\n").join(sharedConfigPaths)
                + "\n, can not write to stdout. Need to specify -w or -f with a single sharedconfig.vdf");
        System.exit(1);
    }

    Tagger.Options taggerOptions = Tagger.Options.fromConfiguration(configuration);

    final String[] removeTagsValues = commandLine.getOptionValues("remove");
    if (null != removeTagsValues) {
        taggerOptions.setRemoveTags(Sets.newHashSet(removeTagsValues));
    }

    Set<TagType> tagTypes = configuration.getTagTypes();
    if (null == tagTypes) {
        System.err.println("no tag types!");
        System.exit(1);
    }

    final boolean printTags = commandLine.hasOption("p");

    final HtmlTagLoader htmlTagLoader = new HtmlTagLoader(pathResolver.findCachePath("html"),
            null == configuration.getCacheExpiryDays() ? 7 : configuration.getCacheExpiryDays());
    final BatchTagLoader tagLoader = new BatchTagLoader(htmlTagLoader, configuration.getDownloadThreads());
    if (true || commandLine.hasOption("v")) {
        tagLoader.registerEventListener(new CliEventLoggerLoaded());
    }
    Tagger tagger = new Tagger(tagLoader);

    if (printTags) {
        Set<String> availableTags = tagger.getAvailableTags(sharedConfigPaths, taggerOptions);
        Joiner.on("\n").appendTo(System.out, availableTags);
    } else {
        for (Path path : sharedConfigPaths) {
            VdfNode tagged = tagger.tag(path, taggerOptions);
            if (commandLine.hasOption("w")) {
                Path backup = path.getParent()
                        .resolve(path.getFileName().toString() + ".bak" + new Date().getTime());
                Files.copy(path, backup, StandardCopyOption.REPLACE_EXISTING);
                System.err.println("backup up " + path + " to " + backup);
                Files.copy(new ByteArrayInputStream(tagged.toPrettyString().getBytes(StandardCharsets.UTF_8)),
                        path, StandardCopyOption.REPLACE_EXISTING);
                try {
                    Files.setPosixFilePermissions(path, SHARED_CONFIG_POSIX_PERMS);
                } catch (Exception e) {
                    System.err.println(e);
                }
                System.err.println("wrote " + path);
            } else {
                System.out.println(tagged.toPrettyString());
                System.err.println("pipe to file and copy to: " + path.toString());
            }
        }
    }
}

From source file:Main.java

private static Path unzip(Path tmpDir, Path zipPath, String name) throws IOException {
    Path outPath = tmpDir.resolve(zipPath.getFileName());
    try (ZipFile zipFile = new ZipFile(zipPath.toFile())) {
        Files.copy(zipFile.getInputStream(zipFile.getEntry(name)), outPath,
                StandardCopyOption.REPLACE_EXISTING);
        return outPath;
    }/*from  w ww . j av  a2s.  co  m*/
}

From source file:com.twitter.heron.apiserver.utils.FileHelper.java

public static boolean copy(InputStream in, Path to) {
    try {//w  w w  .  java  2 s  .c  o m
        Files.copy(in, to, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException ioe) {
        LOG.error("Failed to copy file to {}", to, ioe);
        return false;
    }
    return true;
}

From source file:gov.nist.appvet.shared.FileUtil.java

public static synchronized boolean copyFile(File sourceFile, File destFile) {
    if (sourceFile == null || !sourceFile.exists() || destFile == null) {
        return false;
    }//w  w w  .j a  va 2s .  co m
    try {
        Files.copy(sourceFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (final IOException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:gov.nist.appvet.tool.sigverifier.util.FileUtil.java

public static boolean copyFile(File sourceFile, File destFile) {
    if (sourceFile == null || !sourceFile.exists() || destFile == null) {
        return false;
    }//from ww  w  .java  2  s . c  o m
    try {
        Files.copy(sourceFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (final IOException e) {
        log.error(e.toString());
        return false;
    }
    return true;
}

From source file:com.thesmartguild.firmloader.lib.tftp.TFTPServerFactory.java

public static TFTPServer instantiate(File file) {
    try {/*from  w  ww . j a  v a2 s .com*/
        TFTPServer TFTPServer_;
        Path tmpFilePath = TFTPServerFactory.createTempDirectory();
        Path filePath = Files.copy(file.toPath(), Paths.get(tmpFilePath.toString(), file.getName()),
                StandardCopyOption.REPLACE_EXISTING);
        filePath.toFile().deleteOnExit();
        TFTPServer_ = new TFTPServer(tmpFilePath.toFile(), tmpFilePath.toFile(), ServerMode.GET_ONLY);
        TFTPServer_.setLog(System.out);
        TFTPServer_.setLogError(System.out);
        return TFTPServer_;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.stratio.mojo.scala.crossbuild.FileRewriter.java

private static void backupFile(final File origFile) throws IOException {
    final File bkpFile = getBackupFileName(origFile);
    Files.copy(origFile.toPath(), bkpFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

From source file:com.twitter.heron.apiserver.utils.FileHelper.java

public static boolean copy(Path from, Path to) {
    try {/*  w  w w  . j  av  a  2 s . c o  m*/
        Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException ioe) {
        LOG.error("Failed to copy file from {} to {}", from, to, ioe);
        return false;
    }
    return true;
}