导出txt

@RequestMapping(value = "/txt")
	public void exportTxt(HttpServletRequest request, HttpServletResponse response) {

//导出txt文件
		response.setContentType("text/plain");
		String fileName = "产品信息";

		BufferedOutputStream buff = null;
		StringBuffer write = new StringBuffer();
		ServletOutputStream outSTr = null;
		try {
			response.setHeader("Content-Disposition",
					"attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8") + ".txt");// 导出中文名称
			outSTr = response.getOutputStream();// 建立
			buff = new BufferedOutputStream(outSTr);
			String tab = "\r\n";
			String tcb = "\t";
			write.append("产品名称" + tcb);
			write.append("品牌名称" + tcb);
			write.append("商品条码" + tcb);
			write.append("标准号" + tcb);
			write.append("标准名称" + tcb);
			write.append("标准分类" + tcb);
			write.append("产品规格" + tcb);
			write.append("保质期" + tcb);
			write.append("产品成分" + tcb);
			write.append("下单总数量" + tcb + tab);

			buff.write(write.toString().getBytes("UTF-8"));
			buff.flush();
			buff.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			try {
				buff.close();
				outSTr.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}



// --------------------------------------

导出txt 标准操作

  @RequestMapping(value = "/dldt")
  public void downloadtxt(HttpServletRequest request, HttpServletResponse response) {
    // 获取日志
    // List<DtmSystemLog> list = logService.getLogs();
    // 拼接字符串
    StringBuffer text = new StringBuffer();
    // for(DtmSystemLog log:list){
    text.append("log.getOpeuser()");
    text.append("|");
    text.append("log.getOpedesc()");
    text.append("|");
    text.append("dateString" + new Date().toString());
    text.append("\r\n");// 换行字符
//  }
    exportTxt(response,text.toString());
   
  }
  /*
   * 导出txt文件
   *
   * @author
   *
   * @param response
   *
   * @param text 导出的字符串
   *
   * @return
   */
  public static void exportTxt(HttpServletResponse response, String text) {
    response.setCharacterEncoding("utf-8");
    // 设置响应的内容类型
    response.setContentType("text/plain");
    // 设置文件的名称和格式
    response.addHeader("Content-Disposition",
        "attachment;filename=" + genAttachmentFileName("文件名称", "JSON_FOR_UCC_")// 设置名称格式,没有这个中文名称无法显示
            + ".txt");
    BufferedOutputStream buff = null;
    ServletOutputStream outStr = null;
    try {
      outStr = response.getOutputStream();
      buff = new BufferedOutputStream(outStr);
      buff.write(text.getBytes("UTF-8"));
      buff.flush();
      buff.close();
    } catch (Exception e) {
      // LOGGER.error("导出文件文件出错:{}",e);
    } finally {
      try {
        buff.close();
        outStr.close();
      } catch (Exception e) {
        // LOGGER.error("关闭流对象出错 e:{}",e);
      }
    }
  }
  // 防止中文文件名显示出错
  public static String genAttachmentFileName(String cnName, String defaultName) {
    try {
      cnName = new String(cnName.getBytes("gb2312"), "ISO8859-1");
    } catch (Exception e) {
      cnName = defaultName;
    }
    return cnName;
  }

  

zip下载

/**
   * 将一组文件打zip包
   *
   * @param srcFiles
   * @param targetFileName
   * @throws IOException
   */
  public static void filesToZip(List<File>  srcFiles, String targetFileName) throws IOException  {
    String fileOutName = targetFileName + ".zip";
    byte[] buf = new byte[1024*1024];
    FileInputStream in = null;
    FileOutputStream fos = null;
    ZipOutputStream out = null;
    try {
      fos = new FileOutputStream(fileOutName);
      out = new ZipOutputStream(fos);
      for (File file : srcFiles) {
        in = new FileInputStream(file);
        out.putNextEntry(new  ZipEntry(file.getName()));
        int len;
        while ((len = in.read(buf)) != -1) {
          out.write(buf, 0, len);
        }
        if (in != null) {
          in.close();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (in != null) {
        in.close();
      }
      if (fos != null) {
        out.closeEntry();
        out.close();
        fos.close();
      }
    }
  }

导出ZIP

package com.example.demo;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipThread {

    static final int BUFFER = 8192;

    private File zipFile;

    public ZipThread(String pathName) {
        zipFile = new File(pathName);
    }

    public void compress(String... pathName) {
        ZipOutputStream out = null;
        try {
//            java.util.zip包中另外一些比较重要的类是Adler32和CRC32,它们实现了java.util.zip.Checksum接 口,
//            并估算了压缩数据的校验和(checksum)。众所周知,在运算速度方面,
//            Adler32算法比CRC32算法要有一定的优势;但在数据可信度方 面,CRC32算法则要更胜一筹。
            FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
            CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,
                    new CRC32());
            out = new ZipOutputStream(cos);
            String basedir = "";
            for (int i = 0; i < pathName.length; i++) {
                compress(new File(pathName[i]), out, basedir);
            }
            out.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void compress(String srcPathName) {
        File file = new File(srcPathName);
        if (!file.exists())
            throw new RuntimeException(srcPathName + "不存在!");
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
            CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,
                    new CRC32());
            ZipOutputStream out = new ZipOutputStream(cos);
            String basedir = "";
            compress(file, out, basedir);
            out.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void compress(File file, ZipOutputStream out, String basedir) {
        /* 判断是目录还是文件 */
        if (file.isDirectory()) {
            System.out.println("压缩:" + basedir + file.getName());
            this.compressDirectory(file, out, basedir);
        } else {
            System.out.println("压缩:" + basedir + file.getName());
            this.compressFile(file, out, basedir);
        }
    }

    /**
     * 压缩一个目录
     */
    private void compressDirectory(File dir, ZipOutputStream out, String basedir) {
        if (!dir.exists())
            return;

        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            /* 递归 */
            compress(files[i], out, basedir + dir.getName() + "/");
        }
    }

    /**
     * 压缩一个文件
     */
    private void compressFile(File file, ZipOutputStream out, String basedir) {
        if (!file.exists()) {
            return;
        }
        try {
            BufferedInputStream bis = new BufferedInputStream(
                    new FileInputStream(file));
            ZipEntry entry = new ZipEntry(basedir + file.getName());
            out.putNextEntry(entry);
            int count;
            byte data[] = new byte[BUFFER];
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            bis.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
//测试
    public static void main(String[] args) {
            ZipThread zc = new ZipThread("C:\\Users\\63575\\Desktop\\07/ce.zip");
            zc.compress("C:\\data\\lib","C:\\home\\yanxiuhair\\logs","C:\\mvn\\src\\test\\java");
    }

}


文件下载工具类

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


public class DownloadUtil {

ByteArrayOutputStream baos = new ByteArrayOutputStream();

//这个是spring的工具类 ,是下面注释代码的实现
StreamUtils.copy(baos.toByteArray(), os);

/*
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
baos.close();
os = response.getOutputStream();
byte[] b = new byte[10240];
int length;
while ((length = bais.read(b))> 0)
os.write(b, 0, length);
os.flush();
os.close();
bais.close();*/
 
    /**
     * @param filePath 要下载的文件路径
     * @param returnName 返回的文件名
     * @param response HttpServletResponse
     * @param delFlag 是否删除文件
     */
    protected void download(String filePath,String returnName,HttpServletResponse response,boolean delFlag){
        this.prototypeDownload(new File(filePath), returnName, response, delFlag);
    }




    /**
     * @param file 要下载的文件
     * @param returnName 返回的文件名
     * @param response HttpServletResponse
     * @param delFlag 是否删除文件
     */
    protected void download(File file,String returnName,HttpServletResponse response,boolean delFlag){
        this.prototypeDownload(file, returnName, response, delFlag);
    }
    
    /**
     * @param file 要下载的文件
     * @param returnName 返回的文件名
     * @param response HttpServletResponse
     * @param delFlag 是否删除文件
     */
    public void prototypeDownload(File file,String returnName,HttpServletResponse response,boolean delFlag){
        // 下载文件
        FileInputStream inputStream = null;
        ServletOutputStream outputStream = null;
        try {
            if(!file.exists()) return;
            response.reset();
            //设置响应类型    PDF文件为"application/pdf",WORD文件为:"application/msword", EXCEL文件为:"application/vnd.ms-excel"。  
            response.setContentType("application/octet-stream;charset=utf-8");


            //设置响应的文件名称,并转换成中文编码
            //returnName = URLEncoder.encode(returnName,"UTF-8");
            returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1"));    //保存的文件名,必须和页面编码一致,否则乱码
            
            //attachment作为附件下载;inline客户端机器有安装匹配程序,则直接打开;注意改变配置,清除缓存,否则可能不能看到效果
            response.addHeader("Content-Disposition",   "attachment;filename="+returnName);  
            
            //将文件读入响应流
            inputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();
            int length = 1024;
            int readLength=0;
            byte buf[] = new byte[1024];
            readLength = inputStream.read(buf, 0, length);
            while (readLength != -1) {
                outputStream.write(buf, 0, readLength);
                readLength = inputStream.read(buf, 0, length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //删除原文件
            
            if(delFlag) {                
                file.delete();
            }
        }
    }


    /**
     * by tony 天赐
     * @param byteArrayOutputStream 将文件内容写入ByteArrayOutputStream
     * @param response HttpServletResponse    写入response
     * @param returnName 返回的文件名
     */
    public void download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName) throws IOException{
        response.setContentType("application/octet-stream;charset=utf-8");
        returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1"));            //保存的文件名,必须和页面编码一致,否则乱码
        response.addHeader("Content-Disposition",   "attachment;filename=" + returnName);  
        response.setContentLength(byteArrayOutputStream.size());
        
        ServletOutputStream outputstream = response.getOutputStream();    //取得输出流
        byteArrayOutputStream.writeTo(outputstream);                    //写到输出流
        byteArrayOutputStream.close();                                    //关闭
        outputstream.flush();                                            //刷数据
    }
}