有时需要用到程序下载某个网络资源,比如图片,word文档,pdf,web页面等,网上也有很多,这里用到重写一下,方便热后直接使用,懒人计划.... : )
直接看看方法
public class Funs {
public static String downloadNetFile(String refFileURL, String refSavePath, String refFileType){
/* parameters:
* 1,refFileURL: is a url of file which exists in international (www)net;
* 2,refSavePath: is path of file which success download and save in it, eg.: e:\path;
* 3,refFileType: is a type of file, eg.: gif or jpg or png or htm or html or ppt or doc or...
*
* return type:
* data type: String, only return a file name or a empty String, not include path
* */
String retValue = "";
if(null == refFileURL || refFileURL.trim().isEmpty()
|| null == refSavePath || refSavePath.trim().isEmpty()
|| null == refFileType || refFileType.trim().isEmpty()){
retValue = "";
}else{
//default value of fileName
String fileName = "down_" + new SimpleDateFormat("yyyyMMdd_HHmmssSSS").format(Calendar.getInstance().getTime());
String fileType = refFileType.trim();
if(!fileType.startsWith(".")){
fileType = "." + fileType;
}
fileName = fileName + fileType;
String savePath = refSavePath.trim();
if(!savePath.endsWith("\\")){
savePath = savePath + "\\";
}
String saveDownFile = savePath + fileName;
String fileURL = refFileURL.trim();
try {
//create URL object
URL fileUrl = new URL(fileURL);
//connect to net URL resource and create HttpURLConnection object
HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection();
//also can to use BufferedInputStream and BufferedOutputStream object
//get net source input stream
DataInputStream ins = new DataInputStream(connection.getInputStream());
//rewrite the new file content if exists same file
DataOutputStream out = new DataOutputStream(new FileOutputStream(saveDownFile,false));
byte[] buffer = new byte[4096];
int count = 0;
while ((count = ins.read(buffer)) > 0){
out.write(buffer, 0, count);
}
out.close(); //close dataInputStream and release resource
ins.close(); //close dataOutputStream and release resource
connection.disconnect(); //close net download stream
retValue = fileName;
} catch (Exception e) {
retValue = "";
}
savePath = null;
fileURL = null;
fileType = null;
}
return retValue;
}
}