简体   繁体   English

Java 打开 URL 将文件保存到特定文件夹

[英]Java opens URL to save file to specific folder

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.对于手册,我有一个 URL,当我将 URL 粘贴到 Chrome 浏览器时,浏览器会自动从该 URL 下载 PDF 文件并保存到“下载”文件夹,而不会提示任何用户输入。 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".但是我希望代码将 PDF 保存到特定文件夹而不是默认文件夹“下载”。 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());
    }
  }

When I had to do that in old versions of Java, I used the following snippet (pure Java, source: Baeldung ).当我不得不在 Java 的旧版本中执行此操作时,我使用了以下代码片段(纯 Java,来源: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).上面的代码在 URL 上打开了一个输入 stream,并将这样的 stream 的字节输出到一个文件 output stream(文件在任何你想要的地方)。

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:此外,从 Java 的更新版本开始,还有其他更短的选项:

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.根据您拥有的 Java 的版本,您可以选择其中之一。 Generally speaking, I suggest you reading through the Baeldung's article and check the one that best suits for you.一般来说,我建议您阅读 Baeldung 的文章,然后选择最适合您的文章。

Here you go. Handles redirects and so on can use and modify as you wish.在这里你go。处理重定向等可以随意使用和修改。 Have fun with it.玩得开心。 All in native Java. Did write this to download some media easily.全部在本地 Java。写这个是为了轻松下载一些媒体。 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();
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM