用Java IO流实现下载文件

用Java IO流实现下载文件if file exists 如果文件不存在 进行处理 int i 1 0 系统会报错 除数不能为 0 return modules cms front themes site getTheme frontError InputStream inputStream null OutputStream

if(!file.exists()){

//如果文件不存在,进行处理

int i=1/0;//系统会报错,除数不能为0.

// return “modules/cms/front/themes/”+site.getTheme()+”/frontError”;

}



InputStream inputStream = null;

OutputStream outputStream = null;

//创建缓冲区

byte[] b= new byte[1024];

int len = 0;

try {

//读取要下载的文件,保存到文件输入流

inputStream = new FileInputStream(file);

outputStream = response.getOutputStream();

response.setContentType(“application/force-download”);

String filename = file.getName();

//设置响应头,控制浏览器下载该文件

response.addHeader(“Content-Disposition”,”attachment; filename=” + URLEncoder.encode(filename, “UTF-8”));

response.setContentLength( (int) file.length( ) );

//循环将输入流中的内容读取到缓冲区当中

while((len = inputStream.read(b)) != -1){

//输出缓冲区的内容到浏览器,实现文件下载

outputStream.write(b, 0, len);

}



} catch (Exception e) {

e.printStackTrace();

}finally{

if(inputStream != null){

try {

inputStream.close();

inputStream = null;

} catch (IOException e) {

e.printStackTrace();

}

}

if(outputStream != null){

try {

outputStream.close();

outputStream = null;

} catch (IOException e) {

e.printStackTrace();

}

}

}



return null;

}

在链接中加入该访问地址即可。

编程小号
上一篇 2025-04-05 21:06
下一篇 2025-07-29 19:17

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/142298.html