java io流文件损坏_java使用io流下载.docx. xlsx文件,出现文件损坏提示

在使用Java IO流从服务器下载.docx和.xlsx文件时,可能出现文件损坏提示。通过调整代码,特别是注释掉特定部分,可以避免这个问题。文章详细介绍了代码修改方法,确保文件正确下载。
摘要由CSDN通过智能技术生成

介绍

在使用io流下载服务器上的资源文件时,出现以下提示:但是选择“是”后文件可以正常打开

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

参考 代码如下:

[codesyntax lang="java"]

@RequestMapping(value = "downLoadInstruction")

public void downLoadInstruction(HttpServletRequest request,HttpServletResponse response) {

BufferedOutputStream out = null;

InputStream is = null;

try {

response.reset();

response.setCharacterEncoding("UTF-8");

String filename = "专家信息管理系统使用说明.docx";

response.setContentType("application/msword");

String templatePath = request.getSession().getServletContext().getRealPath("/template/instructionsForUse.docx");

//下载是否使用的火狐浏览器

String agent = request.getHeader("User-Agent");

boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1);

if(isMSIE){

response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename, "UTF-8"));

}else{

response.setHeader("Content-Disposition", "attachment;filename="+ new String(filename.getBytes("UTF-8"), "ISO-8859-1"));

}

out = new BufferedOutputStream(response.getOutputStream());

is = new BufferedInputStream(new FileInputStream(new File(templatePath)));

byte[] content = new byte[1024];

int len = 0;

while ((len = is.read(content)) > 0) {

out.write(content, 0, len);

}

//注释1

//out.write(content);

out.flush();

} catch (Exception e) {

e.printStackTrace();

}finally{

try {

if(is!=null){

is.close();

}

if(out!=null){

out.close();

}

} catch (Exception e2) {

e2.printStackTrace();

}

}

}

[/codesyntax]

代码中需要将注释1的地方注释掉,不然就会出现文件损坏,原因在于“尝试每次读取1024个字节,写入buffer数组,如果少于1024,就会返回实际读取的字节,os.write(buffer);可能多了“。

查看原文:http://surenpi.com/2017/01/03/java%e4%bd%bf%e7%94%a8io%e6%b5%81%e4%b8%8b%e8%bd%bd-docx-xlsx%e6%96%87%e4%bb%b6%ef%bc%8c%e5%87%ba%e7%8e%b0%e6%96%87%e4%bb%b6%e6%8d%9f%e5%9d%8f%e6%8f%90%e7%a4%ba/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值