@shyann
You can save a file from a URL in Java by using the url.openStream()
method to read the content of the URL and then writing it to a file using the FileOutputStream
class. Here's an example code snippet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; public class FileDownloader { public static void main(String[] args) { String url = "https://example.com/file.txt"; String savePath = "file.txt"; try { URL fileUrl = new URL(url); InputStream in = fileUrl.openStream(); FileOutputStream out = new FileOutputStream(savePath); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } in.close(); out.close(); System.out.println("File saved successfully."); } catch (Exception e) { e.printStackTrace(); } } } |
Replace the url
variable with the URL of the file you want to download and the savePath
variable with the path where you want to save the file. When you run this code, it will download the file from the specified URL and save it to the specified path.