package t;
import java.io.*;
import java.net.*;
public class HttpGet {
public final static boolean DEBUG = true; //调试用
private static int BUFFER_SIZE = 8096; //缓冲区大小
/**
* 将HTTP资源另存为文件
*
* @param destUrl String
* @param fileName String
* @throws Exception
*/
public void saveToFile(String destUrl, String fileName) throws IOException {
FileOutputStream fos = null;
BufferedInputStream bis = null;
HttpURLConnection httpUrl = null;
URL url = null;
byte[] buf = new byte[BUFFER_SIZE];
int size = 0;
//建立链接
url = new URL(destUrl);
httpUrl = (HttpURLConnection) url.openConnection();
//连接指定的资源
httpUrl.connect();
//获取网络输入流
bis = new BufferedInputStream(httpUrl.getInputStream());
//建立文件
fos = new FileOutputStream(fileName);
if (this.DEBUG) {
System.out.println("正在获取链接[" + destUrl + "]的内容...\n将其保存为文件[" + fileName + "]");
}
//保存文件
while ( (size = bis.read(buf)) != -1) {
fos.write(buf, 0, size);
}
fos.close();
bis.close();
httpUrl.disconnect();
}
public static void main(String argv[]) {
HttpGet oInstance = new HttpGet();
String url = "http://www.zhcw.com/data-js/data50.js";
String fileName = "E:\\tt.js";
try {
oInstance.saveToFile(url, fileName);
}
catch (Exception err) {
System.out.println(err.getMessage());
}
}
}
2000年3月1日星期三
Java自动下载指定URl的文件
订阅:
博文评论 (Atom)
没有评论:
发表评论