通过action下载文件并给文件重命名,线程下载文件(二)

2014-11-24 07:48:34 · 作者: · 浏览: 3
j end
} else {
getResponse().getWriter().write("<script>alert('该文献暂时无法提供相关下载!!');window.history.back(-1);");
}
return null;
}

}
}

public class DownLoadThread implements Runnable {

/**
*
*/
private static final long serialVersionUID = 9116090002778797074L;

//文件地址 www.2cto.com
private String downUrl;
//存放文件地址
private String fileAddr;

//httpServletResponse
private HttpServletResponse response;
public String getDownUrl() {
return downUrl;
}

public void setDownUrl(String downUrl) {
this.downUrl = downUrl;
}

public String getFileAddr() {
return fileAddr;
}

public void setFileAddr(String fileAddr) {
this.fileAddr = fileAddr;
}

public HttpServletResponse getResponse() {
return response;
}

public void setResponse(HttpServletResponse response) {
this.response = response;
}

@Override
public void run() {
// 服务器返回的状态

int HttpResult = 0;

// 创建URL
URL url = null;
URLConnection urlconn = null;
try {
url = new URL(downUrl);
urlconn = url.openConnection();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

/* HttpURLConnection httpconn = (HttpURLConnection) urlconn;

try {
HttpResult = httpconn.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
}

//System.out.println(HttpResult);

// 不等于HTTP_OK说明连接不成功System.out.print("fail");
System.out.println("HttpResult="+HttpResult+",downUrl="+downUrl);
if (HttpResult != HttpURLConnection.HTTP_OK) {
try {
System.out.println("getResponse()="+this.getResponse().getWriter());
this.getResponse().getWriter().write("<script>alert('连接不成功,下载失败!!')");
} catch (IOException e) {
e.printStackTrace();
}
} else {*/

// 取数据长度System.out.println(filesize);
// int filesize = urlconn.getContentLength();

BufferedInputStream re = null;
BufferedOutputStream ot = null;
try {
re = new BufferedInputStream(urlconn.getInputStream());
ot = new BufferedOutputStream(new FileOutputStream(fileAddr));

// 创建存放输入流的缓冲
byte[] buffer = new byte[1024];
int num = -1; // 读入的字节数

while ((num = re.read(buffer)) != -1) {
ot.write(buffer, 0, num);
}

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
re.close();
ot.close();
} catch (IOException e) {
e.printStackTrace();
}

}

//}

}

public static void main(String[] args) {
new Thread(new DownLoadThread()).start();
}

}

摘自 wangxiaojing123的专栏