前不久写了个下载文件的方法。经过一段时间在程序中的运用,发现了几个问题。修正一下:
public static File saveToFiles(String destUrl,String path) throws IOException {
final int BUFFER_SIZE = 4096;
System.out.println("file download url is "+destUrl+" path is"+path+"--------------");
FileOutputStream fos = null;
BufferedInputStream bis = null;
HttpURLConnection httpconn = null;
URL url = null;
byte[] buf = new byte[BUFFER_SIZE];
int size = 0;
if(rc.isUseProxy()){ // 此处为读取配置文件的内容,确定是否使用代理
Properties prop = System.getProperties();
//set http proxy addr
prop.setProperty("http.proxyHost", rc.getHttpProxyHost()); //设置代理的Ip
// set http proxy port
prop.setProperty("http.proxyPort", rc.getHttpProxyPort()+""); //设置代理的端口
}
File storeFile = new File(path,System.currentTimeMillis()+".tmp");
System.out.println("file download url is "+destUrl+"path is "+path+"---------------");
// connection
url = new URL(destUrl);
httpconn = (HttpURLConnection) url.openConnection();
httpconn.setRequestProperty("Host", "analigesto.com");
httpconn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.0.18) Gecko/2010021501 Ubuntu/9.04 (jaunty) Firefox/3.0.18");
httpconn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpconn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.5");
httpconn.setRequestProperty("Accept-Encoding", "gzip,deflate");
httpconn.setRequestProperty("Accept-Charset", "gb2312,utf-8;q=0.7,*;q=0.7");
httpconn.setRequestProperty("Keep-Alive", "300");
httpconn.setRequestProperty("Connection", "Keep-Alive");
//httpconn.setRequestProperty("Referer", url);
httpconn.setRequestProperty("Cookie", "PHPSESSID=1d888d20bba26e676811ebf7f0cd109b");
try{
httpconn.setReadTimeout(40000); // 设置读取文件超时时间
httpconn.connect();
int statuscode = httpconn.getResponseCode(); // 建立链接后先查询url的状态码
if(statuscode == 200){ //链接正常。并得到了返回信息
bis = new BufferedInputStream(httpconn.getInputStream()); // 建立管道,准备读取数据流
fos = new FileOutputStream(storeFile);
System.out.println("it is to receive link[" + destUrl + "]content/n be save file is:[" + storeFile
+ "]");
while ((size = bis.read(buf)) != -1){ // 保存文件到本地磁盘
fos.write(buf, 0, size);
}
System.out.println("file download url is "+destUrl+" path is"+path+" "+new Date());
fos.close();
bis.close();
httpconn.disconnect();
System.out.println("saveToFiles file is "+storeFile.getName()+" size is "+storeFile.length());
}else{
return null;
}
}catch(Exception e){
System.out.println(destUrl+" this url connection timeout ");
System.out.println(e.toString());
return null;
}
return storeFile;
}