java文件下载的几种方式_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java文件下载的几种方式

java文件下载的几种方式

 2011/10/19 8:04:54  xiaofeng_dream  http://xiaofeng-dream.iteye.com  我要评论(0)
  • 摘要:packagecom.huawei.download;importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io
  • 标签:文件 Java 下载 方式
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流关闭失败");
}
}
}
}
发表评论
用户名: 匿名