下载网络资源方法-java版

有时需要用到程序下载某个网络资源,比如图片,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;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值