Home > Enterprise >  Java opens URL to save file to specific folder
Java opens URL to save file to specific folder

Time:04-20

I'm trying to code based on the manual operation. For manual, I have a URL and when I paste the URL to the Chrome browser, the browser automatically downloads the PDF file from that URL and save to folder "download" without prompting any user input. With Code, I'm able to accomplish the same thing as the manual operation. However I would like the code to save the PDF into specific folder instead of default folder "download". Is it possible to do that?

    public static void browseURL() {
    try {
            
        String url ="mycompanyURL";
        System.out.println("url "   url );
        
        Desktop desktop = Desktop.getDesktop();
        URI uri = new URI (url);            
        desktop.browse(uri);
        
        
    }catch(Exception err) {

        System.out.println("exception "   err.getMessage());
    }
  }

CodePudding user response:

When I had to do that in old versions of Java, I used the following snippet (pure Java, source: Baeldung).

public void streamFromUrl(String downloadUrl, String filePath) throws IOException {
    File file = new File(filePath);
    try (BufferedInputStream in = new BufferedInputStream(new URL(downloadUrl).openStream());
         FileOutputStream fileOutputStream = new FileOutputStream(file)) {
        byte[] dataBuffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
            fileOutputStream.write(dataBuffer, 0, bytesRead);
        }
    }
}

The above opens an input stream on the URL, and outputs the bytes of such stream into a file output stream (where the file is wherever you wish).

Alternatively, there are many libraries doing that in one/two liners (the article I posted shows some of those alternatives).

Also, starting from more recent versions of Java, there are other shorter options:

public void streamFromUrl(String downloadUrl, String filePath) throws IOException {
    try (InputStream in = new URL(downloadUrl).openStream()) {
        Files.copy(in, Paths.get(new File(filePath)), StandardCopyOption.REPLACE_EXISTING);
    }
}

Depending on the version of Java you have, you may pick one of those. Generally speaking, I suggest you reading through the Baeldung's article and check the one that best suits for you.

CodePudding user response:

Here you go. Handles redirects and so on can use and modify as you wish. Have fun with it. All in native Java. Did write this to download some media easily. This can also download media like images, videos and documents.

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.Builder;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.file.Files;
import java.nio.file.Path;

public class Downloader {
    public static void download(String url) {
        final HttpClient hc = HttpClient.newHttpClient();
        final Builder requestBuilder = HttpRequest.newBuilder().version(HttpClient.Version.HTTP_1_1);
        
        Path path = Path.of("myfilepath");
        handleGet(hc, "myfile.pdf", "myurl.com", path, requestBuilder);
        
    }

    private static void handleGet(
                final HttpClient hc, 
                final String fileName, 
                final String url,
                final Path filePath, 
                final Builder requestBuilder
                ) {
            
            final HttpRequest request = requestBuilder.uri(URI.create(url)).build();
            hc.sendAsync(request, BodyHandlers.ofInputStream())
            .thenApply(resp -> {
                int sc = resp.statusCode();
                System.out.println("STATUSCODE: " sc " for url '" url "'");
                if(sc >= 200 && sc < 300) return resp;
                if(sc == 302) {                 
                    System.out.println("Handling 302...");
                    String newUrl = resp.headers().firstValue("location").get();
                    
                    handleGet(hc, fileName, newUrl, filePath, requestBuilder);
                }
                return resp;
            })
            .thenAccept(resp -> {
                int sc = resp.statusCode();
                if(sc >= 200 && sc < 300) {                 
                    try {
                        System.out.println("Im fine here");
                        Files.copy(resp.body(), filePath);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    System.err.println("STATUSCODE: "  sc  " for file "  fileName);
                }
            }).join();
        }
}
  •  Tags:  
  • java
  • Related