Java File Download: URLConnection Method
In Java, you can use the URLConnection class to download files. Here is a simple example code:
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class FileDownloader {
public static void downloadFile(String url, String outputFile) {
try {
URL fileUrl = new URL(url);
URLConnection connection = fileUrl.openConnection();
InputStream inputStream = connection.getInputStream();
FileOutputStream outputStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
downloadFile("http://example.com/file.jpg", "file.jpg");
}
}
In the example above, the downloadFile method takes the URL of the file to download and the path to save it locally as parameters. It uses the URLConnection class to open a connection to the URL and get the input stream, then uses the FileOutputStream class to save the file content to the local file. Finally, it closes the input stream and output stream and outputs a message indicating the download was successful. You can replace the URL of the file to download and the path to save it locally with your own values.