java文件下載代碼實(shí)例(單文件下載和多文件打包下載)
這篇文章主要介紹了java文件下載代碼實(shí)例(單文件下載和多文件打包下載),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
最近項(xiàng)目有需要寫(xiě)文件下載相關(guān)代碼,這邊提交記錄下相關(guān)代碼模塊,寫(xiě)的不太好,后期再優(yōu)化相關(guān)代碼,有好的建議,可留言,謝謝。
1)單文件下載
public String oneFileDownload(HttpServletRequest request,HttpServletResponse response){ //針對(duì)需求需要與需求溝通下載文件傳遞參數(shù) //目前demo文件名是文件的hashCode值+后綴名的方式命名,可以默認(rèn)該hashCode值為文件唯一id String fileName = request.getParameter("fileName"); if(StringUtils.isBlank(fileName)){ return "文件名為空"; } String filePath = request.getSession().getServletContext().getRealPath("/convert")+File.separator+fileName;//目前文件默認(rèn)在該文件夾下,后續(xù)變動(dòng)需修改 File downloadFile = new File(filePath); if(downloadFile.exists()){ OutputStream out = null; FileInputStream fis = null; BufferedInputStream bis = null; try { if(downloadFile.isDirectory()){ return "路徑錯(cuò)誤僅指向文件夾"; } out = response.getOutputStream();// 創(chuàng)建頁(yè)面返回方式為輸出流,彈出下載框 fis = new FileInputStream(downloadFile); bis = new BufferedInputStream(fis); response.setContentType("application/pdf; charset=UTF-8");//設(shè)置編碼字符 response.setHeader("Content-disposition", "attachment;filename=" + fileName); byte[] bt = new byte[2048]; int size = 0; while((size=bis.read(bt)) != -1){ out.write(bt, 0, size); } } catch (Exception e) { e.printStackTrace(); }finally { try { //關(guān)閉流 out.flush(); if(out != null){ out.close(); } if(bis != null){ bis.close(); } if(fis != null){ fis.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return "下載成功"; }else{ return "文件不存在!"; } }
2)多文件打包下載
a)下載指定文件夾下的文件,如果嵌套文件夾也支持(但文件名需要唯一)
public String zipDownload(HttpServletRequest request,HttpServletResponse response) throws IOException{ String sourceFilePath = request.getSession().getServletContext().getRealPath("/convert");//文件路徑 String destinFilePath = request.getSession().getServletContext().getRealPath("/fileZip"); String fileName = FileUtil.zipFiles(sourceFilePath, destinFilePath); File file = new File(destinFilePath+File.separator+fileName); response.setHeader("Content-disposition", "attachment;filename=" + fileName); if(file.exists()){ FileInputStream fis = null; BufferedInputStream bis = null; OutputStream out = response.getOutputStream(); try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); byte[] bufs = new byte[1024 * 10]; int read = 0; while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) { out.write(bufs, 0, read); } } catch (FileNotFoundException e) { e.printStackTrace(); }finally { if(bis != null){ bis.close(); } if(out!=null){ out.close(); } File zipFile = new File(destinFilePath+File.separator+fileName); if(zipFile.exists()){ zipFile.delete(); } } }else{ return "文件壓縮失敗"; } return "下載成功"; }
b)下載指定文件夾下的所有文件,支持樹(shù)型結(jié)構(gòu)
public String zipDownloadRelativePath(HttpServletRequest request,HttpServletResponse response) { String msg ="";//下載提示信息 String root = request.getSession().getServletContext().getRealPath("/convert");//文件路徑 Vector<File> fileVector = new Vector<File>();//定義容器裝載文件 File file = new File(root); File [] subFile = file.listFiles(); //判斷文件性質(zhì)并取文件 for(int i = 0; i<subFile.length; i++){ if(!subFile[i].isDirectory()){//不是文件夾并且不為空 fileVector.add(subFile[i]);//裝載文件 }else{//是文件夾,再次遞歸遍歷文件夾里面的文件 File [] files = subFile[i].listFiles(); Vector v = FileUtil.getPathAllFiles(subFile[i],new Vector<File>()); fileVector.addAll(v);//把迭代的文件裝到容器中 } } //設(shè)置文件下載名稱(chēng) SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); String fileName = dateFormat.format(new Date())+".zip"; response.setHeader("Content-disposition", "attachment;filename=" + fileName);//如果有中文需要轉(zhuǎn)碼 //定義相關(guān)流 //用于瀏覽器下載響應(yīng) OutputStream out = null; //用于讀壓縮好的文件 BufferedInputStream bis = null;//用緩存性能會(huì)好一些 //用于壓縮文件 ZipOutputStream zos = null; //創(chuàng)建一個(gè)空的zip文件 String zipBasePath = request.getSession().getServletContext().getRealPath("/fileZip"); String zipFilePath = zipBasePath+File.separator+fileName; File zipFile = new File(zipFilePath); try { if(!zipFile.exists()){//不存在創(chuàng)建一個(gè)新的 zipFile.createNewFile(); } out = response.getOutputStream(); //創(chuàng)建文件輸出流 zos = new ZipOutputStream(new FileOutputStream(zipFile)); //循環(huán)文件,一個(gè)一個(gè)按順序壓縮 for(int i = 0;i< fileVector.size();i++){ System.out.println(fileVector.get(i).getName()+"大小為:"+fileVector.get(i).length()); FileUtil.zipFileFun(fileVector.get(i),root,zos); } //壓縮完成以后必須要在此處執(zhí)行關(guān)閉 否則下載文件會(huì)有問(wèn)題 if(zos != null){ zos.closeEntry(); zos.close(); } byte[] bt = new byte[10*1024]; int size = 0; bis = new BufferedInputStream(new FileInputStream(zipFilePath),10*1024); while((size=bis.read(bt,0,10*1024)) != -1){//沒(méi)有讀完 out.write(bt,0,size); } } catch (Exception e) { e.printStackTrace(); }finally {//關(guān)閉相關(guān)流 try { //避免出異常時(shí)無(wú)法關(guān)閉 if(zos != null){ zos.closeEntry(); zos.close(); } if(bis != null){ bis.close(); } if(out != null){ out.close(); } if(zipFile.exists()){ zipFile.delete();//刪除 } } catch (Exception e2) { System.out.println("流關(guān)閉出錯(cuò)!"); } } return "下載成功"; }
下載輔助工具類(lèi)
package com.hhwy.fileview.utils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Vector; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class FileUtil { /** * 把某個(gè)文件路徑下面的文件包含文件夾壓縮到一個(gè)文件下 * @param file * @param rootPath 相對(duì)地址 * @param zipoutputStream */ public static void zipFileFun(File file,String rootPath,ZipOutputStream zipoutputStream){ if(file.exists()){//文件存在才合法 if(file.isFile()){ //定義相關(guān)操作流 FileInputStream fis = null; BufferedInputStream bis = null; try { //設(shè)置文件夾 String relativeFilePath = file.getPath().replace(rootPath+File.separator, ""); //創(chuàng)建輸入流讀取文件 fis = new FileInputStream(file); bis = new BufferedInputStream(fis,10*1024); //將文件裝入zip中,開(kāi)始打包 ZipEntry zipEntry; if(!relativeFilePath.contains("\\")){ zipEntry = new ZipEntry(file.getName());//此處值不能重復(fù),要唯一,否則同名文件會(huì)報(bào)錯(cuò) }else{ zipEntry = new ZipEntry(relativeFilePath);//此處值不能重復(fù),要唯一,否則同名文件會(huì)報(bào)錯(cuò) } zipoutputStream.putNextEntry(zipEntry); //開(kāi)始寫(xiě)文件 byte[] b = new byte[10*1024]; int size = 0; while((size=bis.read(b,0,10*1024)) != -1){//沒(méi)有讀完 zipoutputStream.write(b,0,size); } } catch (Exception e) { e.printStackTrace(); }finally { try { //讀完以后關(guān)閉相關(guān)流操作 if(bis != null){ bis.close(); } if(fis != null){ fis.close(); } } catch (Exception e2) { System.out.println("流關(guān)閉錯(cuò)誤!"); } } } // else{//如果是文件夾 // try { // File [] files = file.listFiles();//獲取文件夾下的所有文件 // for(File f : files){ // zipFileFun(f,rootPath, zipoutputStream); // } // } catch (Exception e) { // e.printStackTrace(); // } // // } } } /* * 獲取某個(gè)文件夾下的所有文件 */ public static Vector<File> getPathAllFiles(File file,Vector<File> vector){ if(file.isFile()){//如果是文件,直接裝載 System.out.println("在迭代函數(shù)中文件"+file.getName()+"大小為:"+file.length()); vector.add(file); }else{//文件夾 File[] files = file.listFiles(); for(File f : files){//遞歸 if(f.isDirectory()){ getPathAllFiles(f,vector); }else{ System.out.println("在迭代函數(shù)中文件"+f.getName()+"大小為:"+f.length()); vector.add(f); } } } return vector; } /** * 壓縮文件到指定文件夾 * @param sourceFilePath 源地址 * @param destinFilePath 目的地址 */ public static String zipFiles(String sourceFilePath,String destinFilePath){ File sourceFile = new File(sourceFilePath); FileInputStream fis = null; BufferedInputStream bis = null; FileOutputStream fos = null; ZipOutputStream zos = null; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); String fileName = dateFormat.format(new Date())+".zip"; String zipFilePath = destinFilePath+File.separator+fileName; if (sourceFile.exists() == false) { System.out.println("待壓縮的文件目錄:" + sourceFilePath + "不存在."); } else { try { File zipFile = new File(zipFilePath); if (zipFile.exists()) { System.out.println(zipFilePath + "目錄下存在名字為:" + fileName + ".zip" + "打包文件."); } else { File[] sourceFiles = sourceFile.listFiles(); if (null == sourceFiles || sourceFiles.length < 1) { System.out.println("待壓縮的文件目錄:" + sourceFilePath + "里面不存在文件,無(wú)需壓縮."); } else { //讀取sourceFile下的所有文件 Vector<File> vector = FileUtil.getPathAllFiles(sourceFile, new Vector<File>()); fos = new FileOutputStream(zipFile); zos = new ZipOutputStream(new BufferedOutputStream(fos)); byte[] bufs = new byte[1024 * 10]; for (int i = 0; i < vector.size(); i++) { // 創(chuàng)建ZIP實(shí)體,并添加進(jìn)壓縮包 ZipEntry zipEntry = new ZipEntry(vector.get(i).getName());//文件不可重名,否則會(huì)報(bào)錯(cuò) zos.putNextEntry(zipEntry); // 讀取待壓縮的文件并寫(xiě)進(jìn)壓縮包里 fis = new FileInputStream(vector.get(i)); bis = new BufferedInputStream(fis, 1024 * 10); int read = 0; while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) { zos.write(bufs, 0, read); } } } } } catch (FileNotFoundException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { // 關(guān)閉流 try { if (null != bis) bis.close(); if (null != zos) zos.closeEntry(); zos.close(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } } return fileName; } }
這邊自測(cè)試全部可以正常使用,代碼質(zhì)量不高
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。
上一篇:SpringBoot基于數(shù)據(jù)庫(kù)實(shí)現(xiàn)定時(shí)任務(wù)過(guò)程解析
欄 目:Java
下一篇:基于SPRINGBOOT配置文件占位符過(guò)程解析
本文標(biāo)題:java文件下載代碼實(shí)例(單文件下載和多文件打包下載)
本文地址:http://mengdiqiu.com.cn/a1/Java/8844.html
您可能感興趣的文章
- 01-10Java實(shí)現(xiàn)動(dòng)態(tài)模擬時(shí)鐘
- 01-10利用Java實(shí)現(xiàn)復(fù)制Excel工作表功能
- 01-10JavaWeb實(shí)現(xiàn)郵件發(fā)送功能
- 01-10java基于poi導(dǎo)出excel透視表代碼實(shí)例
- 01-10Java實(shí)現(xiàn)動(dòng)態(tài)數(shù)字時(shí)鐘
- 01-10基于Java驗(yàn)證jwt token代碼實(shí)例
- 01-10java實(shí)現(xiàn)液晶數(shù)字字體顯示當(dāng)前時(shí)間
- 01-10淺談Java中真的只有值傳遞么
- 01-10Java動(dòng)態(tài)顯示當(dāng)前日期和時(shí)間
- 01-10如何解決線(xiàn)程太多導(dǎo)致java socket連接池出現(xiàn)的問(wèn)題


閱讀排行
- 1C語(yǔ)言 while語(yǔ)句的用法詳解
- 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹(shù)的示例代碼(圣誕
- 3利用C語(yǔ)言實(shí)現(xiàn)“百馬百擔(dān)”問(wèn)題方法
- 4C語(yǔ)言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
- 5c語(yǔ)言計(jì)算三角形面積代碼
- 6什么是 WSH(腳本宿主)的詳細(xì)解釋
- 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
- 8正則表達(dá)式匹配各種特殊字符
- 9C語(yǔ)言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
- 10C語(yǔ)言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
本欄相關(guān)
- 01-10Java實(shí)現(xiàn)動(dòng)態(tài)模擬時(shí)鐘
- 01-10Springboot中@Value的使用詳解
- 01-10JavaWeb實(shí)現(xiàn)郵件發(fā)送功能
- 01-10利用Java實(shí)現(xiàn)復(fù)制Excel工作表功能
- 01-10Java實(shí)現(xiàn)動(dòng)態(tài)數(shù)字時(shí)鐘
- 01-10java基于poi導(dǎo)出excel透視表代碼實(shí)例
- 01-10java實(shí)現(xiàn)液晶數(shù)字字體顯示當(dāng)前時(shí)間
- 01-10基于Java驗(yàn)證jwt token代碼實(shí)例
- 01-10Java動(dòng)態(tài)顯示當(dāng)前日期和時(shí)間
- 01-10淺談Java中真的只有值傳遞么
隨機(jī)閱讀
- 01-10使用C語(yǔ)言求解撲克牌的順子及n個(gè)骰子
- 01-10delphi制作wav文件的方法
- 01-10C#中split用法實(shí)例總結(jié)
- 01-10SublimeText編譯C開(kāi)發(fā)環(huán)境設(shè)置
- 01-11Mac OSX 打開(kāi)原生自帶讀寫(xiě)NTFS功能(圖文
- 01-11ajax實(shí)現(xiàn)頁(yè)面的局部加載
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
- 04-02jquery與jsp,用jquery
- 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什
- 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?