By the way, I decided to implement the following movement in Java local application in business.
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.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
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