Java: Download the file and save it in the location selected in the dialog [Use HttpClient]

Introduction

By the way, I decided to implement the following movement in Java local application in business.

  1. Open a dialog to select the save destination
  2. Save the file downloaded from the specified URL to the selected save destination It's a process that seems to be quite common, so I checked if there was an article that could be used as it is ~~ Copy and paste ~~ About each process such as Open dialog, ʻDownload file from URL and save` There was an article, but I couldn't find a complete one. Since it's a big deal, I wrote it in combination.

Below sample

pom.xml


<!--abridgement-->
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.2</version>
    </dependency>
<!--abridgement-->

DownloadSample.java


import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.swing.JFileChooser;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class DownloadSample {
  //Download URL
  static String downloadUrl = "http://sample.com/hoge.txt";

  public static void main(String[] args) throws IOException {
    //Get the default file name from the URL.
    URL url = new URL(downloadUrl);
    String fileName = Paths.get(url.getPath()).getFileName().toString();

    //Display save dialog
    JFileChooser filechooser = new JFileChooser(fileName);
    //Specify the default file name
    filechooser.setSelectedFile(new File(fileName));
    //Show save dialog
    if (filechooser.showSaveDialog(null) != JFileChooser.APPROVE_OPTION) {
      //Exit when pressed other than "Save"
      return;
    }
    //Set save destination
    File saveFile = filechooser.getSelectedFile();
    try (
        //Set HttpClient
        final CloseableHttpClient client = HttpClients.createDefault();
        // Get
        final CloseableHttpResponse response = client.execute(new HttpGet(downloadUrl))) {
      //Check the status and save the file if communication is successful
      final int status = response.getStatusLine().getStatusCode();
      if (status >= 200 && status < 300) {
        final HttpEntity entity = response.getEntity();
        //Save file
        Files.write(Paths.get(saveFile.toString()),
            entity == null ? new byte[0] : EntityUtils.toByteArray(entity));
      } else {
        throw new ClientProtocolException("Unexpected response status: " + status);
      }
    }
  }
}

It's really just this sample, so it may not be necessary ... GitHub

References

Download and save the [Java] file (using Apache HttpComponents HttpClient 4.5.2) → Most of Http communication and file saving have been diverted from this article. Thank you! Display the "Save File" dialog Tips for using JFileChooser conveniently → I referred to this article for how to select the save dialog. Thank you! How to use java.net.URL and a little memo of NIO.2 → For the process of getting the file name from the URL, I referred to this article. Thank you!

Recommended Posts

Java: Download the file and save it in the location selected in the dialog [Use HttpClient]
Specify the java location in eclipse.ini
Unzip the zip file in Java
JSON in Java and Jackson Part ③ Embed JSON in HTML and use it from JavaScript
[Java] How to use the File class
The story of forgetting to close a file in Java and failing
Memo: [Java] If a file is in the monitored directory, process it.
[Java] Use cryptography in the standard library
I want to download a file on the Internet using Ruby and save it locally (with caution)
[Java8] Search the directory and get the file
Is it possible to put the library (aar) in the Android library (aar) and use it?
I received the data of the journey (diary application) in Java and visualized it # 001
How to ZIP a JAVA CSV file and manage it in a Byte array
I can't remember the text file input / output in Java, so I summarized it.
Regarding the transient modifier and serialization in Java
Capture and save from selenium installation in Java
[Java] Read the file in src / main / resources
Upload and download notes in java on S3
[Android development] Get an image from the server in Java and set it in ImageView! !!
[AWS Lambda] Resize the image saved in S3 and save it in another S3 (using Ruby)
How to save a file with the specified extension under the directory specified in Java to the list
Write ABNF in Java and pass the email address
Import the instance and use it on another screen
Write a class in Kotlin and call it in Java
[Java] Get the file in the jar regardless of the environment
[Java] Get the file path in the folder with List
Java classes and instances to understand in the figure
[Swift] Use UserDefaults to save data in the app
21 Load the script from a file and execute it
Use of Abstract Class and Interface properly in Java
Gzip-compress byte array in Java and output to file
How to write comments in the schema definition file in GraphQL Java and reflect them in GraphQL and GraphQL Playground
Use OpenCV in Java
Use PreparedStatement in Java
Copy and paste the file contents in Ubuntu's Docker container
JSON in Java and Jackson Part 1 Return JSON from the server
Implement Java Interface in JRuby class and call it from Java
How to call and use API in Java (Spring Boot)
Correct the character code in Java and read from the URL
Reasons to use Servlet and JSP separately in Java development
Think about the differences between functions and methods (in Java)
Get attributes and values from an XML file in Java
[Java] Use ResolverStyle.LENIENT to handle the date and time nicely
[Rails] Get access_token at the time of Twitter authentication with Sorcery and save it in DB
Convert Excel to Blob with java, save it, read it from DB and output it as a file!
Graph the sensor information of Raspberry Pi in Java and check it with a web browser