To download a file from a URL in Java, you can use the URL
and URLConnection
classes from the java.net
package to open a connection to the file, and the InputStream
and OutputStream
classes from the java.io
package to read and write the file.
Here's an example of how to download a file from a URL in Java:
import java.io.*; import java.net.*; public class FileDownloader { public static void main(String[] args) throws IOException { // Define the URL of the file to download String fileUrl = "https://example.com/files/myfile.txt"; // Open a connection to the URL URL url = new URL(fileUrl); URLConnection connection = url.openConnection(); // Set the user agent to pretend to be a web browser connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"); // Connect to the URL connection.connect(); // Get the input stream to read the file InputStream inputStream = connection.getInputStream(); // Create a file output stream to save the file FileOutputStream outputStream = new FileOutputStream("myfile.txt"); // Create a buffer to improve download speed byte[] buffer = new byte[4096]; int bytesRead; // Read the file from the input stream and write it to the output stream while ((bytesRead = inputStream.read(buffer)) != -1)