package tt;
import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.commons.httpclient.HttpException;
public class DownFile {
private static int buffer_size = 8096;//缓冲区大小
private Vector vdownload = new Vector();//url列表
private Vector vfilelist = new Vector();//下载后的保存文件名列表
/**
* 构造方法
*/
public DownFile() {
}
/**
* 清除下载列表
*/
public void resetlist() {
vdownload.clear();
vfilelist.clear();
}
/**
* 增加下载列表项
*
* @param url string
* @param filename string
*/
public void additem(String url, String filename) {
vdownload.add(url);
vfilelist.add(filename);
}
/**
* 根据列表下载资源
*/
public void downloadbylist() {
String url = null;
String filename = null;
// 按列表顺序保存资源
for (int i = 0; i < vdownload.size(); i++) {
url = (String) vdownload.get(i);
filename = (String) vfilelist.get(i);
try {
savetofile(url, filename);
}
catch (IOException err) {
Func.cout("资源[" + url + "]下载失败!!!");
}
}
}
/**
* 将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);
Func.cout("正在获取链接[" + desturl + "]的内容.../n将其保存为文件[" + filename + "]");
// 保存文件
while ( (size = bis.read(buf)) != -1)
fos.write(buf, 0, size);
fos.close();
bis.close();
httpurl.disconnect();
Func.cout("下载成功!");
}
/**
* 设置代理服务器
*
* @param proxy string
* @param proxyport string
public void setproxyserver(String proxy, String proxyport) {
// 设置代理服务器
if(debug)System.getProperties().put("proxyset", "true");
if(debug)System.getProperties().put("proxyhost", proxy);
if(debug)System.getProperties().put("proxyport", proxyport);
} */
/**
* 设置认证用户名与密码
*
* @param uid string
* @param pwd string
public void setauthenticator(String uid, String pwd) {
authenTicator.setdefault(new myAuthenticator(uid, pwd));
}*/
public static void main(String[] args) throws HttpException, IOException {
String url = "http://www.engineeringvillage2.com.cn/controller/servlet/Controller?CID=quickSearchCitationFormat&database=1&searchWord1=liu ye xiang §ion1=AU&yearselect=yearrange&startYear=1990&endYear=2008"; try {//下载存盘
DownFile down = new DownFile();
down.savetofile(url, "D:/test.html");
}
catch (Exception e) {
Func.cout(e.getMessage());
Func.coute("资源[" + url + "]下载失败!!!");
}
String html = null;
try{//将下载的文件读入html
FileInputStream fis=new FileInputStream("D:/test.html");
int size = fis.available();
byte b[] = new byte[size];
if(fis.read(b,0,size)>0){
html = new String(b);
}
}
catch(Exception e) {
Func.cout(e.getMessage());
Func.coute("资源[" + "D:/test.html" + "]读取失败!!!");
}
System.out.println( html);
}
}