直接改动文件路径就能够。其它都不须要改动,帮助类已经为大家写好,可直接使用

1、Scroller:

/**
* 下载文件
* @author liupeng
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value="/testFileDown")
public String testFileDown(HttpServletRequest request,HttpServletResponse response)throws Exception{
FileOperator.FileDownload("e:"+File.separator+"tt.pdf", response);
return null;
}

2、FileOperator:

package com.utcsoft.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import com.utcsoft.common.servlet.Log4jInitServlet;
public class FileOperator {
private final static Log logger = LogFactory.getLog(FileOperator.class); public static String path = "c:";
public static int count = 0; public FileOperator(){
String tmp = getClass().getResource("/").getPath();
System.out.println(tmp);
} public static String getRootPath(){
try{
String proName = Log4jInitServlet.propertiesPath;
String tmp = System.getProperty("user.dir");
path = tmp.substring(0, tmp.lastIndexOf(File.separator) + 1) + "bid" + File.separator; /*String osName = System.getProperties().getProperty("os.name");
if (osName.toLowerCase().indexOf("windows") == -1)
{
path = "/home/bid/";
}*/
InputStream in = new BufferedInputStream(new FileInputStream(proName));
Properties p = new Properties();
p.load(in);
//p.containsKey("path.file")
if(!p.getProperty("path.file").toString().trim().equals("")){
path = p.getProperty("path.file");
}
}
catch(Exception ex){
logger.error("[FileOperator] - 获取文件存放路径出现异常 - " + ex.getMessage());
}
return path;
}
//传送文件流到服务端
public static void FileUpload(String filePath, HttpServletRequest request)throws ServletException, IOException{
OutputStream out = null;
InputStream ins = null;
try {
ins = request.getInputStream();
out = new FileOutputStream(filePath); byte[] fileData = new byte[1024];
int readCount = 0 ;
count = 0; while((readCount=ins.read(fileData,0,1024)) != -1){
out.write(fileData,0,readCount);
count += readCount;
}
out.flush();
logger.info("[FileUpload] - read file size:"+count + "=======" + request.getClass() + ":" + filePath);
}catch(Exception ex){
ex.printStackTrace();
logger.error("[FileUpload] - " + ex + "=======" + request.getClass());
}finally {
out.close();
ins.close();
}
} //传送文件流到服务端
public static String loadString(String path) throws IOException
{
StringBuffer buf = new StringBuffer();
String line = null;
java.io.File file = new java.io.File(path);
java.io.InputStream in = null;
java.io.OutputStream out = null;
java.io.BufferedReader reader = null;
try
{
//获取fileInputStream流;
in = new java.io.FileInputStream(file);
//获取bufferedReader流;
reader = new java.io.BufferedReader(new java.io.InputStreamReader(
in));
//循环读取行,假设读取的行为null时,则退出循环;
while ((line = reader.readLine()) != null)
{
buf.append(line).append("\n");
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
reader.close();
in.close();
}
return buf.toString();
}
//在线保存并写文件
public static void ReadFile(String path1, String path2) throws IOException {
OutputStream out = new FileOutputStream(path2);
try {
// 创建文件流对象
FileInputStream is = new FileInputStream(path1); // 设定读取的字节数
int n = 512;
byte buffer[] = new byte[n];
int readCount = 0 ;
count = 0;
// 读取输入流
while ((readCount=is.read(buffer, 0, n) )!= -1) {
out.write(buffer,0,readCount);
count += readCount;
}
out.flush();
// 关闭输入流
out.close();
is.close();
}
catch (IOException ioe) {
}
} //传送文件流到client
public static void FileDownload(String filePath, HttpServletResponse response)throws ServletException, IOException{
if("".equals(filePath))
return;
OutputStream out = null;
InputStream ins = null;
try {
String fileName = StringOperator.GetFileName(filePath);
File file = new File(filePath);
long fileLength = file.length(); ins = new FileInputStream(filePath);
out = response.getOutputStream(); byte[] fileData = new byte[1024];
int readCount = 0 ;
count = 0;
//response.setHeader("Content-Type", "application/octet-stream");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename="+URLEncoder.encode(fileName,"UTF-8"));
response.setHeader("Content-Length", String.valueOf(fileLength)); while((readCount=ins.read(fileData,0,1024)) != -1){
out.write(fileData,0,readCount);
count += readCount;
}
out.flush();
response.flushBuffer();
logger.info("[FileDownload] - write file size:"+count + "=======" + response.getClass() + ":" + filePath);
}catch(Exception ex){
ex.printStackTrace();
logger.error("[FileDownload] -" + ex+ "=======" + response.getClass());
}
finally {
out.close();
ins.close();
}
//PrintWriter out1 = response.getWriter();
//out.clear();
//out = pageContext.pushBody();
} //文件上传--測试通过
public static boolean FileUploadEx(String filePath, String fileName, long fileSize, InputStream inputStream){
boolean flag = false; try{
//filePath = StringOperator.GetEncodeString(filePath);
//fileName = StringOperator.GetEncodeString(fileName);
logger.info("[FileUploadEx] - filePath="+filePath+" fileName="+fileName); InputStream in = inputStream;
File filed = new File(filePath);
if (!filed.exists()) {
filed.mkdirs();
}
byte[] buffer = new byte[4096];
File outFile = new File(filePath + File.separator + fileName);
FileOutputStream bos = null;
bos = new java.io.FileOutputStream(outFile);
int read;
long yx = 0; while ((read = in.read(buffer)) != -1) {
yx = yx + read;
bos.write(buffer, 0, read);
} in.close();
bos.flush();
bos.close();
logger.info("[FileUploadEx] - file size:{" + fileSize + "}, read:{" + yx + "}");
flag = true; }catch(Exception ex){
logger.error(ex);
}
return flag;
} public static void writefile(String filepath) {
File file = new File(path); //要写入的文件
BufferedWriter writer = null;
try {
if (!file.exists())
file.createNewFile(); writer = new BufferedWriter(new FileWriter(file));
writer.write("111111111111111111111");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 依据路径删除指定的文件夹或文件,不管存在与否
*@param sPath 要删除的文件夹或文件
*@return 删除成功返回 true,否则返回 false。 */
public static boolean DeleteFolder(String sPath) {
boolean flag = false;
File file = new File(sPath);
// 推断文件夹或文件是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
} else {
return deleteDirectory(sPath);
}
}
/**
* 删除单个文件
* @param sPath 被删除文件的文件名称
* @return 单个文件删除成功返回true,否则返回false
*/
public static boolean deleteFile(String sPath) {
boolean flag = false;
File file = new File(sPath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}
/**
* 删除文件夹(文件夹)以及文件夹下的文件
* @param sPath 被删除文件夹的文件路径
* @return 文件夹删除成功返回true。否则返回false
*/
public static boolean deleteDirectory(String sPath) {
//假设sPath不以文件分隔符结尾,自己主动加入文件分隔符
if (!sPath.endsWith(File.separator)) {
sPath = sPath + File.separator;
}
File dirFile = new File(sPath);
//假设dir相应的文件不存在,或者不是一个文件夹,则退出
if (!dirFile.exists() || !dirFile.isDirectory()) {
return false;
}
boolean flag = true;
//删除文件夹下的全部文件(包含子文件夹)
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
//删除子文件
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag) break;
} //删除子文件夹
else {
flag = deleteDirectory(files[i].getAbsolutePath());
if (!flag) break;
}
}
if (!flag) return false;
//删除当前文件夹
if (dirFile.delete()) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
path = "F:\\test";
boolean result = FileOperator.DeleteFolder(path);
System.out.println(result); } //能够先将选择的全部的文件生成一个zip文件,然后再下载,该zip文件,就可以实现批量下载
public static void ZipOutputStreamDemo(String zipsPath,String sourcefile) throws Exception {
byte[] buffer = new byte[1024];
//生成的ZIP文件名称为Demo.zip
String strZipName = "C:Demo.zip"; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipName)); //须要同一时候下载的两个文件result.txt 。source.txt File[] file1 = { new File("C:\\test.pdf"),new File("C:\\test11.pdf")}; for(int i=0;i<file1.length;i++) { FileInputStream fis = new FileInputStream(file1[i]); out.putNextEntry(new ZipEntry(file1[i].getName())); int len; //读入须要下载的文件的内容,打包到zip文件 while((len = fis.read(buffer))>0) { out.write(buffer,0,len); } out.closeEntry(); fis.close(); } out.close(); System.out.println("生成Demo.zip成功");
}
}

文件下载-SpringMVC中測试的更多相关文章

  1. 【翻译自mos文章】ABMR:在asm 环境中測试Automatic Block Recover 特性的方法

    ABMR:在asm 环境中測试Automatic Block Recover 特性的方法 參考原文: ABMR: How to test Automatic Block Recover Feature ...

  2. intel dpdk在ubuntu12.04中測试testpmd、helloworld程序

    一.測试环境 操作系统:ubuntu12.04   x86_64 dpdk版本号:1.6.0r2 虚拟机:vmware 10 网卡: Intel Corporation 82545EM Gigabit ...

  3. java 搭建webservice服务+testclient測试

    整理别人的日志: 一.什么是webservice 一种构建应用程序的普遍模型,能够在不论什么支持网络通信的操作系统中执行.一种新的web应用程序分支,能够公布.定位通过web调用.它是一个应用组件,为 ...

  4. Android单元測试之JUnit

    随着近期几年測试方面的工作慢慢火热起来.常常看见有招聘測试project师的招聘信息.在Java中有单元測试这么一个JUnit 方式,Android眼下主要编写的语言是Java,所以在Android开 ...

  5. C++ 学习笔记3,struct长度測试,struct存储时的对齐方式

    之所以专门为struct的长度写一篇測试,是由于原来c++对于struct的变量, 在分配内存的时候,c++对struct有一种特殊的存储机制. 看以下的測试: 一.在Windows7 32bit , ...

  6. caffe在windows编译project及执行mnist数据集測试

    caffe在windows上的配置和编译能够參考例如以下的博客: http://blog.csdn.net/joshua_1988/article/details/45036993 http://bl ...

  7. ios的单元測试OCUnit以及更新了之后的XCTestCase

    1.像一般创建项目的步骤一样.创建一个用于測试的项目或者打开一个待測试的项目. (oc是5.0之前所使用的測试,如今用的是XCtestCase,默认会创建一个主的測试类.曾经版本号可能非常多步骤省去) ...

  8. 【JUnit4.10源码分析】3.4 Description与測试树

    Description使用组合模式描写叙述一个測试树.组合模式中全部元素都是Composite对象. Description有成员变量private final ArrayList<Descri ...

  9. Mock+Proxy在SDK项目的自己主动化測试实战

    项目背景 广告SDK项目是为应用程序APP开发者提供移动广告平台接入的API程序集合,其形态就是一个植入宿主APP的jar包.提供的功能主要有以下几点: - 为APP请求广告内容 - 用户行为打点 - ...

随机推荐

  1. C# MVC 自学笔记—2 MVC Movie简介

    MVC Movie是微软官方的一个MVC入门项目,我们可以跟着这个项目来实践入门 这是官方地址 http://www.asp.net/mvc/tutorials/mvc-4/getting-start ...

  2. ios23- 文件下载(同步和异步)

    1.第一步:创建一个单例视图 #import <UIKit/UIKit.h> @interface ios23_downViewController : UIViewController& ...

  3. 开发人员福利!ChromeSnifferPlus 插件正式登陆 Chrome Web Store

    今天(2014-10-30)下午,ChromeSnifferPlus 插件正式登陆 Chrome Web Store. 在线安装地址: https://chrome.google.com/websto ...

  4. 贴一个CMemDC 代码,这东西真不错噢,短小精悍,可谓极品

    罗索客 发布于 2006-11-28 21:53 点击:3941次  来自: 原文: http://yuantao82.spaces.live.com/Blog/cns!8FC0A772D812A22 ...

  5. windows下eclipse跑junit报错:CreateProcess error=206

    from:http://isuifengfei.iteye.com/blog/1684262 windows下,eclipse中运行junit出现错误提示: Exception occurred ex ...

  6. Android学习4、Android该Adapter

    一.Adapter介绍 An Adapter object acts as a bridge between an AdapterView and the underlying data for th ...

  7. Nancy.Host的Web应用

    Nancy.Host实现脱离iis的Web应用 本篇将介绍如何使用Nancy.Host实现脱离iis的Web应用,在开源任务管理平台TaskManagerV2.0代码里面已经使用了Nancy.Host ...

  8. vs2008编译QT开源项目三国杀(五篇文章)

    请参看 http://tieba.baidu.com/f?kz=1508964881 按照上面的网址教程,下载三国杀源码,swig工具,并下载最新的QT4.8.2 for vs2008.我本机已经安装 ...

  9. 通过设置Referer反"反盗链"

    package cn.searchphoto.util; import java.io.File; import java.io.FileOutputStream; import java.io.In ...

  10. Google 搜索的基本语法

    ★搜索引擎的选择 先简单说一下"搜索引擎的选择". 在咱们天朝,Google 屡屡被 GFW 骚扰,导致百度占了便宜,成为份额最高的搜索引擎.不过今天这篇教程,俺还是继续拿 Goo ...