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;
}