java程序下载

2024-04-29 16:32:15 架空历史

public class FileDownloader {
public static void main(String[] args) {
String fileUrl = "https://example.com/sample-file.txt"; String saveDir = "/path/to/save/directory/";
// Download file try { URL url = new URL(fileUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1); InputStream inputStream = connection.getInputStream(); FileOutputStream outputStream = new FileOutputStream(saveDir + fileName);
byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); }
outputStream.close(); inputStream.close();
System.out.println("File downloaded successfully!"); } else { System.out.println("Failed to download file. Response code: " + responseCode); } } catch (MalformedURLException e) { System.out.println("Malformed URL: " + e.getMessage()); } catch (IOException e) { System.out.println("IO Exception: " + e.getMessage()); } } }

相关阅读