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(Path source, OutputStream out) throws IOException 

Source Link

Document

Copies all bytes from a file to an output stream.

Usage

From source file:com.github.ansell.shp.SHPDump.java

public static void main(String... args) throws Exception {
    final OptionParser parser = new OptionParser();

    final OptionSpec<Void> help = parser.accepts("help").forHelp();
    final OptionSpec<File> input = parser.accepts("input").withRequiredArg().ofType(File.class).required()
            .describedAs("The input SHP file");
    final OptionSpec<File> output = parser.accepts("output").withRequiredArg().ofType(File.class).required()
            .describedAs("The output directory to use for debugging files");
    final OptionSpec<String> outputPrefix = parser.accepts("prefix").withRequiredArg().ofType(String.class)
            .defaultsTo("shp-debug").describedAs("The output prefix to use for debugging files");
    final OptionSpec<File> outputMappingTemplate = parser.accepts("output-mapping").withRequiredArg()
            .ofType(File.class).describedAs("The output mapping template file if it needs to be generated.");
    final OptionSpec<Integer> resolution = parser.accepts("resolution").withRequiredArg().ofType(Integer.class)
            .defaultsTo(2048).describedAs("The output image file resolution");
    final OptionSpec<String> format = parser.accepts("format").withRequiredArg().ofType(String.class)
            .defaultsTo("png").describedAs("The output image format");
    final OptionSpec<String> removeIfEmpty = parser.accepts("remove-if-empty").withRequiredArg()
            .ofType(String.class).describedAs(
                    "The name of an attribute to remove if its value is empty before outputting the resulting shapefile. Use multiple times to specify multiple fields to check");

    OptionSet options = null;/*  ww  w .j av  a 2  s  .com*/

    try {
        options = parser.parse(args);
    } catch (final OptionException e) {
        System.out.println(e.getMessage());
        parser.printHelpOn(System.out);
        throw e;
    }

    if (options.has(help)) {
        parser.printHelpOn(System.out);
        return;
    }

    final Path inputPath = input.value(options).toPath();
    if (!Files.exists(inputPath)) {
        throw new FileNotFoundException("Could not find input SHP file: " + inputPath.toString());
    }

    final Path outputPath = output.value(options).toPath();
    if (!Files.exists(outputPath)) {
        throw new FileNotFoundException("Output directory does not exist: " + outputPath.toString());
    }

    final Path outputMappingPath = options.has(outputMappingTemplate)
            ? outputMappingTemplate.value(options).toPath()
            : null;
    if (options.has(outputMappingTemplate) && Files.exists(outputMappingPath)) {
        throw new FileNotFoundException(
                "Output mapping template file already exists: " + outputMappingPath.toString());
    }

    final Set<String> filterFields = ConcurrentHashMap.newKeySet();
    if (options.has(removeIfEmpty)) {
        for (String nextFilterField : removeIfEmpty.values(options)) {
            System.out.println("Will filter field if empty value found: " + nextFilterField);
            filterFields.add(nextFilterField);
        }
    }

    if (!filterFields.isEmpty()) {
        System.out.println("Full set of filter fields: " + filterFields);
    }

    final String prefix = outputPrefix.value(options);

    FileDataStore store = FileDataStoreFinder.getDataStore(inputPath.toFile());

    if (store == null) {
        throw new RuntimeException("Could not read the given input as an ESRI Shapefile: "
                + inputPath.toAbsolutePath().toString());
    }

    for (String typeName : new LinkedHashSet<>(Arrays.asList(store.getTypeNames()))) {
        System.out.println("");
        System.out.println("Type: " + typeName);
        SimpleFeatureSource featureSource = store.getFeatureSource(typeName);
        SimpleFeatureType schema = featureSource.getSchema();

        Name outputSchemaName = new NameImpl(schema.getName().getNamespaceURI(),
                schema.getName().getLocalPart().replace(" ", "").replace("%20", ""));
        System.out.println("Replacing name on schema: " + schema.getName() + " with " + outputSchemaName);
        SimpleFeatureType outputSchema = SHPUtils.changeSchemaName(schema, outputSchemaName);

        List<String> attributeList = new ArrayList<>();
        for (AttributeDescriptor attribute : schema.getAttributeDescriptors()) {
            System.out.println("Attribute: " + attribute.getName().toString());
            attributeList.add(attribute.getName().toString());
        }
        CsvSchema csvSchema = CSVUtil.buildSchema(attributeList);

        SimpleFeatureCollection collection = featureSource.getFeatures();
        int featureCount = 0;
        Path nextCSVFile = outputPath.resolve(prefix + ".csv");
        Path nextSummaryCSVFile = outputPath
                .resolve(prefix + "-" + outputSchema.getTypeName() + "-Summary.csv");
        List<SimpleFeature> outputFeatureList = new CopyOnWriteArrayList<>();

        try (SimpleFeatureIterator iterator = collection.features();
                Writer bufferedWriter = Files.newBufferedWriter(nextCSVFile, StandardCharsets.UTF_8,
                        StandardOpenOption.CREATE_NEW);
                SequenceWriter csv = CSVUtil.newCSVWriter(bufferedWriter, csvSchema);) {
            List<String> nextLine = new ArrayList<>();
            while (iterator.hasNext()) {
                SimpleFeature feature = iterator.next();
                featureCount++;
                if (featureCount <= 2) {
                    System.out.println("");
                    System.out.println(feature.getIdentifier());
                } else if (featureCount % 100 == 0) {
                    System.out.print(".");
                }
                boolean filterThisFeature = false;
                for (AttributeDescriptor attribute : schema.getAttributeDescriptors()) {
                    String featureString = Optional.ofNullable(feature.getAttribute(attribute.getName()))
                            .orElse("").toString();
                    nextLine.add(featureString);
                    if (filterFields.contains(attribute.getName().toString())
                            && featureString.trim().isEmpty()) {
                        filterThisFeature = true;
                    }
                    if (featureString.length() > 100) {
                        featureString = featureString.substring(0, 100) + "...";
                    }
                    if (featureCount <= 2) {
                        System.out.print(attribute.getName() + "=");
                        System.out.println(featureString);
                    }
                }
                if (!filterThisFeature) {
                    outputFeatureList.add(SHPUtils.changeSchemaName(feature, outputSchema));
                    csv.write(nextLine);
                }
                nextLine.clear();
            }
        }
        try (Reader csvReader = Files.newBufferedReader(nextCSVFile, StandardCharsets.UTF_8);
                Writer summaryOutput = Files.newBufferedWriter(nextSummaryCSVFile, StandardCharsets.UTF_8,
                        StandardOpenOption.CREATE_NEW);
                final Writer mappingWriter = options.has(outputMappingTemplate)
                        ? Files.newBufferedWriter(outputMappingPath)
                        : NullWriter.NULL_WRITER) {
            CSVSummariser.runSummarise(csvReader, summaryOutput, mappingWriter,
                    CSVSummariser.DEFAULT_SAMPLE_COUNT, false);
        }
        if (featureCount > 100) {
            System.out.println("");
        }
        System.out.println("");
        System.out.println("Feature count: " + featureCount);

        SimpleFeatureCollection outputCollection = new ListFeatureCollection(outputSchema, outputFeatureList);
        Path outputShapefilePath = outputPath.resolve(prefix + "-" + outputSchema.getTypeName() + "-dump");
        if (!Files.exists(outputShapefilePath)) {
            Files.createDirectory(outputShapefilePath);
        }
        SHPUtils.writeShapefile(outputCollection, outputShapefilePath);

        // Create ZIP file from the contents to keep the subfiles together
        Path outputShapefileZipPath = outputPath
                .resolve(prefix + "-" + outputSchema.getTypeName() + "-dump.zip");
        try (final OutputStream out = Files.newOutputStream(outputShapefileZipPath,
                StandardOpenOption.CREATE_NEW);
                final ZipOutputStream zip = new ZipOutputStream(out, StandardCharsets.UTF_8);) {
            Files.list(outputShapefilePath).forEachOrdered(Unchecked.consumer(e -> {
                zip.putNextEntry(new ZipEntry(e.getFileName().toString()));
                Files.copy(e, zip);
                zip.closeEntry();
            }));
        }

        try (final OutputStream outputStream = Files.newOutputStream(
                outputPath.resolve(prefix + "." + format.value(options)), StandardOpenOption.CREATE_NEW);) {
            MapContent map = new MapContent();
            map.setTitle(prefix + "-" + outputSchema.getTypeName());
            Style style = SLD.createSimpleStyle(featureSource.getSchema());
            Layer layer = new FeatureLayer(new CollectionFeatureSource(outputCollection), style);
            map.addLayer(layer);
            SHPUtils.renderImage(map, outputStream, resolution.value(options), format.value(options));
        }
    }
}

From source file:com.github.exper0.efilecopier.ftp.FtpInboundChannelAdapterSample.java

@Test
public void runDemo() throws Exception {
    Files.copy(this.getClass().getResourceAsStream("/test-files/a.txt"),
            Paths.get(TestSuite.FTP_ROOT_DIR, "a.txt"));
    Files.copy(this.getClass().getResourceAsStream("/test-files/b.txt"),
            Paths.get(TestSuite.FTP_ROOT_DIR, "b.txt"));
    FtpReportSettings settings = new FtpReportSettings();
    settings.setPort(4444);/*w  w  w. ja v  a2 s  .  c  o  m*/
    settings.setHost("localhost");
    settings.setLocalDir(LOCAL_FTP_TEMP_DIR + "/ftpInbound");
    settings.setRemoteDir("/");
    settings.setUser("demo");
    settings.setPassword("demo");
    FtpAdapterFactory factory = new FtpAdapterFactory();
    try (FileAdapter adapter = factory.createAdapter(settings)) {
        adapter.activate();
        PollableChannel ftpChannel = adapter.channel();
        Message<?> message1 = ftpChannel.receive(2000);
        Message<?> message2 = ftpChannel.receive(2000);
        Message<?> message3 = ftpChannel.receive(1000);

        LOGGER.info(String.format("Received first file message: %s.", message1));
        LOGGER.info(String.format("Received second file message: %s.", message2));
        LOGGER.info(String.format("Received nothing else: %s.", message3));

        assertNotNull(message1);
        assertNotNull(message2);
        assertNull("Was NOT expecting a third message.", message3);
    }
}

From source file:de.alexkamp.sandbox.model.SandboxData.java

public SandboxData copyTo(File source, String target) throws IOException {
    File targetFile = new File(basePath, target);
    if (source.isDirectory()) {
        SandboxUtils.copyDirectory(source, targetFile);
    } else {/*from w ww . j av a  2 s  .com*/
        ensureExistance(targetFile);
        Files.copy(source.toPath(), targetFile.toPath());
    }
    return this;
}

From source file:com.anuz.dummyclient.controller.ContentController.java

@RequestMapping(value = "files/{directory}/{fileName}", method = RequestMethod.GET)
public void image(@PathVariable("directory") String directory, @PathVariable("fileName") String fileName,
        @RequestHeader HttpHeaders headers, HttpServletResponse response) {
    try {/*from  www.j  a v  a 2 s  .  com*/
        logger.info(fileName);

        File file = new File(CONSTANT.CONTENTS + directory + "/" + fileName);
        Files.copy(file.toPath(), response.getOutputStream());

    } catch (IOException ex) {
        logger.info("Image not found");
        logger.debug(ex.getMessage());
    }
}

From source file:com.streamsets.pipeline.stage.origin.spooldir.TestSpoolDirWithCompression.java

@BeforeClass
public static void setUpClass()
        throws IOException, InterruptedException, URISyntaxException, CompressorException {
    testDir = new File("target", UUID.randomUUID().toString()).getAbsoluteFile();
    Assert.assertTrue(testDir.mkdirs());
    Files.copy(Paths.get(Resources.getResource("logArchive.zip").toURI()),
            Paths.get(testDir.getAbsolutePath(), "logArchive1.zip"));
    Files.copy(Paths.get(Resources.getResource("logArchive.zip").toURI()),
            Paths.get(testDir.getAbsolutePath(), "logArchive2.zip"));
    Files.copy(Paths.get(Resources.getResource("logArchive.tar.gz").toURI()),
            Paths.get(testDir.getAbsolutePath(), "logArchive1.tar.gz"));
    Files.copy(Paths.get(Resources.getResource("logArchive.tar.gz").toURI()),
            Paths.get(testDir.getAbsolutePath(), "logArchive2.tar.gz"));
    Files.copy(Paths.get(Resources.getResource("testAvro.tar.gz").toURI()),
            Paths.get(testDir.getAbsolutePath(), "testAvro1.tar.gz"));
    Files.copy(Paths.get(Resources.getResource("testAvro.tar.gz").toURI()),
            Paths.get(testDir.getAbsolutePath(), "testAvro2.tar.gz"));

    File bz2File = new File(testDir, "testFile1.bz2");
    CompressorOutputStream bzip2 = new CompressorStreamFactory().createCompressorOutputStream("bzip2",
            new FileOutputStream(bz2File));
    bzip2.write(IOUtils.toByteArray(Resources.getResource("testLogFile.txt").openStream()));
    bzip2.close();// w  w  w .ja v  a  2s . c  om

    bz2File = new File(testDir, "testFile2.bz2");
    bzip2 = new CompressorStreamFactory().createCompressorOutputStream("bzip2", new FileOutputStream(bz2File));
    bzip2.write(IOUtils.toByteArray(Resources.getResource("testLogFile.txt").openStream()));
    bzip2.close();
}

From source file:net.portalblockz.portalbot.serverdata.JSONConfigManager.java

public JSONConfigManager(File file) {
    instance = this;
    try {/*from   ww w  .  ja  v a2 s  . com*/
        if (!file.exists()) {
            Path path = file.toPath();
            Files.copy(getClass().getClassLoader().getResourceAsStream("config.json"), path);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    String s;
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        StringBuilder jsonObjectBuilder = new StringBuilder();
        while ((s = reader.readLine()) != null) {
            jsonObjectBuilder.append(s);
        }
        configObject = new JSONObject(jsonObjectBuilder.toString());
        reader.close();

    } catch (Exception e) {

    }
    for (int i = 0; i < getJSONServers().length(); i++) {
        JSONObject server = getJSONServers().getJSONObject(i);
        serverList.add(new Server(server.getString("host"), server.getString("username"),
                server.getString("password"), server.getInt("port"), getList(server, "channels"),
                getList(server, "staff"), server.getString("prefix").charAt(0)));
        System.out.println(String.format("%s %s %s %s %s", server.getString("host"),
                server.getString("username"), server.getString("password"), server.getInt("port"),
                server.getString("prefix").charAt(0)));
    }
    serializeRepos();
    serializeBlacklist();
}

From source file:com.thoughtworks.go.agent.common.util.JarUtil.java

private static File extractJarEntry(JarFile jarFile, JarEntry jarEntry, File targetFile) {
    LOG.debug("Extracting {}!/{} -> {}", jarFile, jarEntry, targetFile);
    try (InputStream inputStream = jarFile.getInputStream(jarEntry)) {
        FileUtils.forceMkdirParent(targetFile);
        Files.copy(inputStream, targetFile.toPath());
        return targetFile;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }/*w  ww  . j  a v a  2s .c om*/
}

From source file:com.curso.ejemplohinputfile.FileUploadBean.java

public String processFileUpload() throws IOException {
    Part uploadedFile = getFile();//from  w  w w. ja  va2  s.c  o  m
    final Path destination = Paths.get("c:/tmp/" + FilenameUtils.getName(getSubmittedFileName(uploadedFile)));
    //Con servlet 3.1
    //final Path destination = Paths.get("c:/tmp/"+ FilenameUtils.getName(uploadedFile.getSubmittedFileName()));
    InputStream bytes = null;
    if (null != uploadedFile) {
        bytes = uploadedFile.getInputStream(); //
        Files.copy(bytes, destination);
    }
    return "success";
}

From source file:Test.java

@Override
public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attributes) throws IOException {
    Path targetDirectory = target.resolve(source.relativize(directory));
    try {/*from w  w  w. ja v  a 2s  .c  o  m*/
        System.out.println("Copying " + source.relativize(directory));
        Files.copy(directory, targetDirectory);
    } catch (FileAlreadyExistsException e) {
        if (!Files.isDirectory(targetDirectory)) {
            throw e;
        }
    }
    return FileVisitResult.CONTINUE;
}

From source file:io.github.binout.wordpress2html.writer.PostWriter.java

public File write() throws IOException {
    String htmlContent = getFullHtml();
    Files.copy(new ByteArrayInputStream(htmlContent.getBytes("UTF-8")), file.toPath());
    if (asciidocConverter.isPresent()) {
        File asciidoc = asciidocConverter.get().convert(file);
        addHeader(asciidoc);/* w w w. jav a2 s .  c  o m*/
    }
    return file;
}