【文件下载】Java下载文件的几种方式

 摘自:https://www.cnblogs.com/sunny3096/p/8204291.html

1.以流的方式下载.

  public HttpServletResponse download(String path, HttpServletResponse response) {
try {
// path是指欲下载的文件的路径。
File file = new File(path);
// 取得文件名。
String filename = file.getName();
// 取得文件的后缀名。
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase(); // 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return response;
}

2.下载本地文件

  public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {
// 下载本地文件
String fileName = "Operator.doc".toString(); // 文件的默认保存名
// 读到流中
InputStream inStream = new FileInputStream("c:/Operator.doc");// 文件的存放路径
// 设置输出的格式
response.reset();
response.setContentType("bin");
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// 循环取出流中的数据
byte[] b = new byte[100];
int len;
try {
while ((len = inStream.read(b)) > 0)
response.getOutputStream().write(b, 0, len);
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

3.下载网络文件

   public void downloadNet(HttpServletResponse response) throws MalformedURLException {
// 下载网络文件
int bytesum = 0;
int byteread = 0; URL url = new URL("windine.blogdriver.com/logo.gif"); try {
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream("c:/abc.gif"); byte[] buffer = new byte[1204];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

4.支持在线打开的方式

  public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0; response.reset(); // 非常重要
if (isOnLine) { // 在线打开方式
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
// 文件名应该编码成UTF-8
} else { // 纯下载方式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}
即使爬到最高的山上,一次也只能脚踏实地地迈一步。

【文件下载】Java下载文件的几种方式的更多相关文章

  1. Java下载文件的几种方式

    转发自博客园Sunny的文章 1.以流的方式下载 public HttpServletResponse download(String path, HttpServletResponse respon ...

  2. java 下载文件的两种方式和java文件的上传

    一:以网络的方式下载文件 try { // path是指欲下载的文件的路径. File file = new File(path); // 以流的形式下载文件. InputStream fis = n ...

  3. 从后端接口下载文件的2种方式:get方式、post方式

    从后端接口下载文件的2种方式 一.get方式 直接使用: location.href='http://www.xxx.com/getFile?params1=xxx&params2=xxxx' ...

  4. java 从网上下载文件的几种方式

    package com.github.pandafang.tool; import java.io.BufferedOutputStream; import java.io.File; import ...

  5. Java读写文件的几种方式

    自工作以后好久没有整理Java的基础知识了.趁有时间,整理一下Java文件操作的几种方式.无论哪种编程语言,文件读写操作时避免不了的一件事情,Java也不例外.Java读写文件一般是通过字节.字符和行 ...

  6. Asp.Net 下载文件的几种方式

    asp.net下载文件几种方式 protected void Button1_Click(object sender, EventArgs e) { /* 微软为Response对象提供了一个新的方法 ...

  7. php下载文件的一种方式

    <?php ob_start(); // $file_name="cookie.jpg"; $file_name="abc.jpg"; //用以解决中文不 ...

  8. asp.net 浏览器下载文件的四种方式

    // 方法一:TransmitFile实现下载 protected void Button1_Click(object sender, EventArgs e) { Response.ContentT ...

  9. C#从服务器下载文件的四种方式

    //方法一:TransmitFile实现下载 string fileName = "ss.docx"; //客户端预设的文件名,导出时可修改  string filePath = ...

随机推荐

  1. 用多个class选择元素

    注意下面两个的区别:  $(".role-developer.role-designer").css("color","red");  $( ...

  2. apache配置修改

    1.如何设置请求等待时间   在httpd.conf里面设置:   TimeOut n   其中n为整数,单位是秒.     2. 3.如何使得apache监听在特定的端口   修改httpd.con ...

  3. PHP判断客户端是PCweb端还是移动手机端方法

    /** * * 根据php的$_SERVER['HTTP_USER_AGENT'] 中各种浏览器访问时所包含各个浏览器特定的字符串来判断是属于PC还是移动端 * @author discuz3x * ...

  4. 7 python 模块间相互导入

    python在不同层级目录import模块的方法 注意,在python3里,即使目录下没__int__.py文件也能创建成功,猜应该是解释器优化所致,但创建包还是要记得加上这个文件 吧. 1.模块的分 ...

  5. rem 响应 js函数

    size();window.onresize = function(){ size();}function size(){ var htnl_o=document.getElementsByTagNa ...

  6. 程序员教程-10章-C++程序设计

    本来这章是不打算写了的,毕竟自己学的是JAVA,C++就不想看了,但毕竟还有一点时间,就把C++也看一下吧 目录结构 10.1 C++程序基础 10.1.1 数据类型 1 基本数据类型 2 常量和变量 ...

  7. ADO数据库编程入门

    ADO 是目前在Windows环境中比较流行的客户端数据库编程技术. ADO是建立在OLE DB底层技术之上的高级编程接口,因而它兼具有强大的数据处理功能(处理各种不同类型的数据源.分布式的数据处理等 ...

  8. com.google.gson的SerializedName解决实体类与关键字的重名

    使用google的gson包,解决实体类中字段与java关键字的重名: // 比如 当实体类中有switch关键字时,解决冲突如下 @SerializedName("switch" ...

  9. Haskell语言学习笔记(50)Extra

    Extra 安装 extra 模块. $ cabal install extra Installed extra-1.6 Prelude> :m +Extra Prelude Extra> ...

  10. 面向对象三大特性一一多态(polymorphism)

    package com.bjsxt.oop.polymorphism; public class Animal { public void voice(){ System.out.println(&q ...