import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
/**
* 图片/音频/等等
*/
public class FileDownloader {
public static void main(String[] args) {
String fileUrl = "http://example.com/001.png"; // 替换为要下载的文件的URL
// 获取文件后缀名
String fileSuffix = fileUrl.substring(fileUrl.lastIndexOf("."));
// 最后上传生成的文件名
String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + fileSuffix;
File outputPath = new File("C:\\text\\"+finalFileName); // 替换为要保存到本地的文件路径
try {
File dir = outputPath.getParentFile();
if (!dir.exists()) {
// 创建文件夹
dir.mkdirs();
}
// 创建文件
outputPath.createNewFile();
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = new BufferedInputStream(connection.getInputStream());
FileOutputStream outputStream = new FileOutputStream(outputPath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("文件已成功下载到:" + outputPath);
} else {
System.out.println("无法下载文件,HTTP响应码:" + connection.getResponseCode());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java下载URL指向的文件并保存到本地
最新推荐文章于 2024-03-21 15:39:05 发布