URL url = new URL("http://localhost:8080/download/aaaa.rar");
URLConnection conn = url.openConnection();
conn.connect(); InputStream in = conn.getInputStream(); byte[] b = null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
int c;
while ((c = in.read()) != -1) {
os.write(c);
}
b = os.toByteArray();
byte[] buffer = new byte[b.length];
in.read(buffer);
response.addHeader("Content-Length", "" + b.length);
response.addHeader("Content-Disposition", "attachment;filename="
+ new String("aaaa.rar"));
request.setCharacterEncoding("gb2312");
OutputStream out = new BufferedOutputStream(response
.getOutputStream());
out.write(buffer);
out.flush();
out.close();
文件能正常下载,但是下载的文件提示已损坏,不管是RAR还是TXT文档,都不能正常打开,各位帮帮忙。

解决方案 »

  1.   

    while ((c = in.read()) != -1) {
        os.write(c);

    //你在上面把能读的东西都读完了
    b = os.toByteArray();
    byte[] buffer = new byte[b.length];
    in.read(buffer); //为什么这里又读了那么多?直接用b不就行了
    //如国我猜的不错的话,in.read(buffer);这一句什么都没读到
    //所以你在下面往外写的时候写的是空的数据,所以下载到的文件是损坏的
    //直接用在下面直接把b写出去就行了