package com.xxxx.service;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
/**
*
* java访问URL并下载文件
* 用于从总管理中心访问分析系统,拿到分析报告;
* @author xxx 2015-01-19
*
*/
public class TestSampleAnalysisReport {
public static void saveToFile(String destUrl, String fileName)
throws IOException {
FileOutputStream fos = null;
BufferedInputStream bis = null;
HttpURLConnection httpUrl = null;
URL url = null;
byte[] buf = new byte[1024];
int size = 0;
url = new URL(destUrl);
httpUrl = (HttpURLConnection) url.openConnection();
httpUrl.connect();
bis = new BufferedInputStream(httpUrl.getInputStream());
fos = new FileOutputStream(fileName);
while ((size = bis.read(buf)) != -1)
fos.write(buf, 0, size);
fos.close();
bis.close();
httpUrl.disconnect();
}
public static void main(String[] args) {
try {
System.out.println("begin");
saveToFile("http://xxxxxxx:8081/tasks/download/1", "d:\\111.doc");
System.out.println("end");
} catch (Exception e) {
e.printStackTrace();
}
}
}
本文介绍了一个 Java 类 TestSampleAnalysisReport,该类提供了一个静态方法 saveToFile,用于通过给定的 URL 下载文件并保存到指定路径。此方法使用 HttpURLConnection 和 BufferedInputStream 实现了基本的网络文件下载功能。
5836

被折叠的 条评论
为什么被折叠?



