java下载远程服务器端数据文件

在java中实现下载远程服务器中的数据文件
/**
	 * 下载服务器端清单文件
	 * 
	 * 
	 */
	public void dowloadFile() {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		try {
			String downPath = PropertyUtil.getProperty("xjgz.task.inf.downPath",
					"attribute.properties");
			//String ftpUrl = PropertyUtil.getProperty("xjgz.task.inf.ftpUrl",
			//"attribute.properties");
			HttpURLConnection httpUrl = null;
	        URL url = null;
	        String urlStr = "http://135.224.78.18:8888";//服务器地址
	        if(fileName.indexOf("/") != -1){
	        	fileName = fileName.replaceAll("/", "-");
	        }
	        String str = encode(urlStr + downPath + "/" + fileName, "utf-8");//需要对数据文件的全链接中的中文字符进行加密
	        url = new URL(str);
	      
			BufferedOutputStream out = null;
			BufferedInputStream in = null;
			try {
				in = new BufferedInputStream(url.openStream());
				response.reset();
	            response.setContentType("application/octet-stream"); 
	            response.setHeader("Content-Disposition",
						"attachment;filename=\"" + URLEncoder.encode(fileName,"UTF-8") + "\"");
	            int i;
	            while((i=in.read())!=-1){
	                response.getOutputStream().write(i);
	            }
	            in.close();
	            response.getOutputStream().close();
			}catch(Exception e){
				e.printStackTrace();
			}
			finally {
				if (in != null) {
					in.close();
					in = null;
				}
				if (out != null) {
					out.close();
					out = null;
				}
			}
			response.flushBuffer();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e2) {
			e2.printStackTrace();
		}

	}
	
	
	/**
	 * * 替换字符串卷 * *
	 * 
	 * @param str
	 *            被替换的字符串 *
	 * @param charset
	 *            字符集 *
	 * @return 替换好的 *
	 * @throws UnsupportedEncodingException
	 *             不支持的字符集
	 */
	public static String encode(String str, String charset)
			throws UnsupportedEncodingException {
		String zhPattern = "[\u4e00-\u9fa5]+";
		Pattern p = Pattern.compile(zhPattern);
		Matcher m = p.matcher(str);
		StringBuffer b = new StringBuffer();
		while (m.find()) {
			m.appendReplacement(b, URLEncoder.encode(m.group(0), charset));
		}
		m.appendTail(b);
		return b.toString();
	}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值