- 1 year ago
Making download in APPDATA
Comment
1 / 1
To download a file and save it in the APPDATA
folder (the application data folder specific to the current user), you can use Java's URLConnection
to fetch the file from a URL and then save it to the APPDATA
folder using the appropriate path. Here's a Java code snippet to achieve that:
javaimport java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class FileDownloader {
public static void main(String[] args) {
String downloadUrl = "https://example.com/samplefile.txt"; // Replace with the URL of the file to download
String appDataPath = System.getenv("APPDATA");
String saveFilePath = appDataPath + File.separator + "samplefile.txt";
try {
downloadFile(downloadUrl, saveFilePath);
System.out.println("File downloaded and saved to: " + saveFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void downloadFile(String fileUrl, String saveFilePath) throws IOException {
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
try (InputStream inputStream = new BufferedInputStream(connection.getInputStream());
FileOutputStream fileOutputStream = new FileOutputStream(saveFilePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
}
}
}
Replace https://example.com/samplefile.txt
with the actual URL of the file you want to download. The downloadFile
method will download the file and save it to the APPDATA
folder with the name samplefile.txt
. You can change the file name and file path as needed.