Issue with Arrays.stream(body.split(" ")).forEach
Asked Answered
P

1

1

Trying to download files from apache.camel.

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;

import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;

@Component
public class Download extends RouteBuilder{


    @Override
    public void configure() throws Exception {

        from("file:files/input")
            .routeId("downloadInitId")
            .to("direct:downloadFiles");
            
        from("direct:downloadFiles")
            .routeId("downloadProcessId")
            .process(p -> {
                String body = p.getIn().getBody(String.class);
                Arrays.stream(body.split(" ")).forEach(s -> {
                    try {
                        URL url = new URL(s);
                        File f = new File(s);
                        System.out.println(f.getName());
                        System.out.println(f.getPath());
                        InputStream in = url.openStream();
                        Files.copy(in, Paths.get(".\\files\\download\\output\\"+f.getName()), StandardCopyOption.REPLACE_EXISTING);
                        in.close();
                    } catch (IOException e) {
                        e.getMessage();
                    }
                });
            });
        
    }

}

I have a files.txt with the content below, that I will dump on files\input folder,

https://github.com/a.zip
https://github.com/b.zip

The outuput will always be like this,

b.zip
https:\github.com\a.zip
https:\github.com\b.zip

Not sure why a.zip is always getting omitted therefore the first will not be downloaded. Or if 3 lines, only last filename will be printed or downloaded.

Polypetalous answered 15/8, 2022 at 5:25 Comment(0)
P
0

Got it.

        from("direct:downloadFiles")
            .routeId("downloadProcessId")
            .split(body().tokenize("\n"))  // add this
            .process(p -> {
                String body = p.getIn().getBody(String.class);
                Arrays.stream(body.split(" ")).forEach(s -> {
                    String sn = s.toString(); // add this
                    sn = sn.replace("\n", "").replace("\r", ""); // add this
                    try {
                        URL url = new URL(sn);  // use sn
                        File f = new File(sn);  // use sn
Polypetalous answered 15/8, 2022 at 14:2 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.