java打包下载需用用到IO 打包流:ZipOutputStream
TXT 文件打包下载:
用到ZipOutputStream zip输出流,InputStream 字节输入流
BufferedInputStream,BufferedOutputStream 缓冲输入输出流
//打包下载
public void bookPackage(OutputStream outputStream,String bookIds,String bookname,String authorname){
ZipOutputStream out = new ZipOutputStream(outputStream); //创建zip输出流
try {
List<Integer> ids=null;
if(bookIds!=null&&!bookIds.equals("")){
ids =Arrays.stream(bookIds.split(",")).map(s->Integer.parseInt(s.trim())).collect(Collectors.toList());
}
List<Book> books = bookMapper.txtPackage(ids, bookname, authorname);
for(Book book:books){
String address = book.getDownload();
if(address!=null){
File f = new File(address);
if(f.exists()){
out.putNextEntry(new ZipEntry(f.getName()));
InputStream input = new FileInputStream(f);
BufferedInputStream bis=new BufferedInputStream(input); //缓冲输入 (获取文件内容)
BufferedOutputStream bos = new BufferedOutputStream(out); //缓冲输出 (输出到zip流里)
byte[] bytes=new byte[1024]; int len=-1;
while ((len=bis.read(bytes))!=-1){
bos.write(bytes,0,len);
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
out.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
@ApiOperation(value="打包下载书籍")
@GetMapping("/downloadbookPL")
public void downloadbookPL(HttpServletRequest request, HttpServletResponse response,
String bookIds,
@ApiParam(value = "书名")@RequestParam(value="bookname",defaultValue = "")String bookname,
@ApiParam(value = "作者")@RequestParam(value="authorname",defaultValue = "")String authorname
){
response.setCharacterEncoding(request.getCharacterEncoding());
InputStream inputStream = null;
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
response.setContentType("application/x-download");//应用程序强制下载
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("打包下载.zip", "UTF-8"));
bookService.bookPackage(outputStream, bookIds,bookname,authorname);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Excel 打包下载:
使用到的流有ZipOutputStream zip输出流,内存输出流
public boolean excelPack(OutputStream outputStream){
ZipOutputStream out = new ZipOutputStream(outputStream); //创建zip输出流
SXSSFWorkbook sxssfWorkbook=null;
List<Book> bookList =bookService .selectAllExcel(null); //获取数据
try {
for (int i=1;i<5;i++){
sxssfWorkbook = bookExcelS(bookList); //生成Excel
if(sxssfWorkbook!=null){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); //内存输出流
sxssfWorkbook.write(byteArrayOutputStream); //Excel 写入内存输出流
out.putNextEntry(new ZipEntry(i + "." + "清单" + ".xlsx")); //添加zip
out.write(byteArrayOutputStream.toByteArray()); //写入
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (out != null) {
try { out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
版权声明:本文为duguyuyun12345原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。