import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.HttpURLConnection;
public class DownloadFile {
public static void main(String[] args) {
String fileURL = "http://example.com/file.zip"; // 文件的URL
String saveDir = "C:\\path\\to\\save"; // 保存文件的本地目录
String fileName = "file.zip"; // 保存的文件名
try {
downloadFile(fileURL, saveDir, fileName);
System.out.println("文件下载成功!");
} catch (IOException e) {
System.out.println("文件下载失败: " + e.getMessage());
}
}
public static void downloadFile(String fileURL, String saveDir, String fileName) throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// 检查HTTP响应码是否为200,表示请求成功
if (responseCode == HttpURLConnection.HTTP_OK) {
String saveFilePath = saveDir + "\\" + fileName;
try (BufferedInputStream in = new BufferedInputStream(httpConn.getInputStream());
FileOutputStream fileOutputStream = new FileOutputStream(saveFilePath)) {
byte[] dataBuffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
}
} else {
throw new IOException("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}
}
java.io和java.net包来处理文件输入输出和网络连接。main方法:设置文件的URL、保存路径和文件名,并调用downloadFile方法进行下载。downloadFile方法:URL对象打开连接。BufferedInputStream和FileOutputStream高效地读写数据。如果需要修改文件URL、保存路径或文件名,可以直接修改代码中的相应变量。
下一篇:java实体转json字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站