java文件下载的几种方式

本文介绍了一个使用Java实现的文件下载工具类,支持从本地文件系统和URL地址下载文件,并提供了详细的代码实现和流程说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.huawei.download;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletResponse;

public class DownloadUtils
{
/**
*
* @param path 服务器目录下的文件路径
* @param response
* @return
*/
public static HttpServletResponse download(String path, HttpServletResponse response)
{
InputStream fis = null;
OutputStream toClient = null;

try
{
//需要下载的文件路径
File file = new File(path);
//取得文件名
String filename = file.getName();
//以流的形式下载文件
fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
//将文件流中的数据读到字节数组中
fis.read(buffer);

//清空response
response.reset();
//设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());

toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
}
catch(IOException e)
{
throw new RuntimeException("IO流操作失败 " + e.toString());
}
finally
{
//统一关闭读写流
try
{
if(fis != null)
{
fis.close();
fis = null;
}

if(toClient != null)
{
toClient.close();
toClient = null;
}
}
catch(IOException e)
{
throw new RuntimeException("流关闭失败" + e.toString());
}
}
return response;
}

/**
* 通过URL下载网络文件
* @param localPath
* @param response
*/
public static void downloadByUrl(String localPath, HttpServletResponse response, URL url)
{
int bytesum = 0;
int byteread = 0;
URLConnection conn = null;
InputStream input = null;
OutputStream output = null;

try
{
conn = url.openConnection();
input = conn.getInputStream();
output = new FileOutputStream(localPath);

byte[] buffer = new byte[1024];
while((byteread = input.read(buffer)) != -1)
{
bytesum += byteread;
output.write(buffer, 0, byteread);
}
}
catch(MalformedURLException e)
{
throw new RuntimeException("URL解析异常");
}
catch(IOException e)
{
throw new RuntimeException("IO流操作异常");
}
finally
{
try
{
if(input != null)
{
input.close();
input = null;
}

if(output != null)
{
output.close();
output = null;
}
}
catch(IOException e)
{
throw new RuntimeException("IO流关闭失败");
}
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值