在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();
}