public void downloadFile(String filesPath,String FileName,String url) throws IOException {
String folderPath = filesPath;
File folder = new File(folderPath);
// 如果文件夹不存在,则创建
if (!folder.exists()) {
boolean created = folder.mkdirs();
if (created) {
log.info("成功创建文件夹:" + folderPath);
} else {
log.info("创建文件夹失败:" + folderPath);
}
}
URL url = new URL(url);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 从响应中获取输入流
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = folderPath + "\\" + fileName;
// 打开本地文件输出流
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
// 复制文件内容到本地文件
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
log.info(fileName+"保存成功");
} else {
log.info("下载失败,HTTP响应代码: " + responseCode);
}
httpConn.disconnect();
}
Java实现文件下载
最新推荐文章于 2024-04-27 23:13:56 发布