【文件下载】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. selenium+python自动化98--文件下载弹窗处理(PyKeyboard)

    前言 在web自动化下载操作时,有时候会弹出下载框,这种下载框不属于web的页面,是没办法去定位的(有些同学一说到点击,脑袋里面就是定位!定位!定位!) 有时候我们并不是非要去定位到这个按钮再去点击, ...

  2. html:模板

    http://www.mycodes.net/code_previewmap.php?id=3461 http://www.17sucai.com/pins/4120.html  欧美风格的CMS企业 ...

  3. 13.从url 输入网址到最终页面渲染完成

    从url 输入网址到最终页面渲染完成,发生了什么? 1.DNS解析:将域名地址解析为IP地址 先读取: -浏览器DNS缓存 -系统DNS缓存 -路由器DNS缓存 -网络运营商DNS缓存 -递归搜索:b ...

  4. bootstrap修改勾选样式

    小对勾需要引入awesome插件. css部分: .bella-checkbox{ position: relative;}/** 将初始的checkbox的样式改变 */.bella-checkbo ...

  5. CSS镂空图片处理

    来源:http://www.zhangxinxu.com/wordpress/?p=5267,分享收藏 使用镂空图片,通过CSS改变颜色,达到图片切换的效果,可以同过背景图,然后改变背景色,从而达到图 ...

  6. 机器学习入门-DBSCAN聚类算法

    DBSCAN 聚类算法又称为密度聚类,是一种不断发张下线而不断扩张的算法,主要的参数是半径r和k值 DBSCAN的几个概念: 核心对象:某个点的密度达到算法设定的阈值则其为核心点,核心点的意思就是一个 ...

  7. 转:Linux设备驱动开发(1):内核基础概念

    一.linux设备驱动的作用 内核:用于管理软硬件资源,并提供运行环境.如分配4G虚拟空间等. linux设备驱动:是连接硬件和内核之间的桥梁. linux系统按个人理解可按下划分: 应用层:包括PO ...

  8. sessionpage1

    session1 <%@page import="java.text.SimpleDateFormat"%> <%@ page language="ja ...

  9. jremoting的功能扩展点

    1  InvokeFilter,实现此接口 可以在consumer端 与provider端的调用过程中拦截住请求调用. 已经实现的InvokeFilter包括 RetryInvokeFilter:实现 ...

  10. python Count类(转)

    1.collections模块 collections模块自Python 2.4版本开始被引入,包含了dict.set.list.tuple以外的一些特殊的容器类型,分别是: OrderedDict类 ...