需求,根據產品ID查詢產品詳情,產品詳情會返回產品的一些文案,以及圖片的url。需要做成,將文案信息記錄在一個txt文檔中,然后圖片下載到文件夾,最后下載到本地,下載后自動刪除剛才生成的文件夾以及文件夾生成的壓縮包等。
例如壓縮包打開是這樣的:

txt文檔是這樣的:

需求已明了,現在開始從頁面點擊下載開始action層:
由於我是每次用戶點擊頁面下載時,生成文件到一個壓縮包,壓縮包存在項目的路徑下的,下載成功后刪除文件以及壓縮包。
/** * 獲取當前產品的文案 * * @return * @throws IOException */ public Resolution getZip() throws IOException { HttpServletResponse response = getContext().getResponse(); Integer i = Integer.valueOf(gysupplierproducts.getProd_code());// JSONArray recal = getDealInfo.getDealInfoForOne(i);//得到產品信息json串 String url = ""; String name = ""; String fileDir = ""; for (int n = 0; n < recal.size(); n++) { Map<String, Object> returnMap = gysupplierproductsService.saveZip(recal.get(n).toString());//解析json串 url = returnMap.get("url").toString(); name = returnMap.get("name").toString(); fileDir = url; try { url = url+".zip"; try { File file = new File(url); File file2 = new File(fileDir); name = name+".zip"; response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=" + new String(name.getBytes("ISO8859-1"), "UTF-8")); response.setContentLength((int) file.length()); response.setContentType("application/zip");// 定義輸出類型 FileInputStream fis = new FileInputStream(file); BufferedInputStream buff = new BufferedInputStream(fis); byte[] b = new byte[1024];// 相當於我們的緩存 long k = 0;// 該值用於計算當前實際下載了多少字節 OutputStream myout = response.getOutputStream();// 從response對象中得到輸出流,准備下載 // 開始循環下載 while (k < file.length()) { int j = buff.read(b, 0, 1024); k += j; myout.write(b, 0, j); } myout.flush(); buff.close(); file.delete();//刪除生成的壓縮包文件 ZipUtils.delAllFile(fileDir);//文件夾下面還有東西,需要全部刪除。 file2.delete(); //刪除生產的文件 } catch (Exception e) { System.out.println(e); } } catch (Exception e) { e.printStackTrace(); } } return null; }
service層,解析JSONArry,記錄文本信息到txt,下載圖片到指定文件夾下。
省略一解析部分:
public Map<String,Object> saveZip(String delStr) throws IOException{ Map<String,Object> returnMap = new HashMap<String, Object>(); returnMap.put("url", ""); returnMap.put("name", ""); JSONObject dealInfo = JSONObject.fromObject(delStr); File directory = new File("");// 參數為空 String courseFile = directory.getCanonicalPath(); //I:\workspace\qhzn-fxxt String fileName = Comb.getComb().replaceAll("-",""); courseFile = courseFile+"\\webapp\\zip\\"+fileName; //I:\workspace\qhzn-fxxt/webapp/zip/425a0c0490704706813593d080329037 System.out.println(courseFile); File dirFile = new File(courseFile); dirFile.mkdir();//創建文件夾 DealBaseInfo baseInfo = (DealBaseInfo)JSONObject.toBean(dealInfo.getJSONObject("baseInfo"), DealBaseInfo.class) ; String title = baseInfo.getTitle();//產品名稱 JSONArray inageArray = JSONArray.fromObject(baseInfoObj.get("imgInfos")); List<ImageInfo> inageList = JSONArray.toList(inageArray, new ImageInfo(), new JsonConfig()); // List<ImageInfo> inageList = baseInfo.getImgInfos(); for (int i = 0; i < inageList.size(); i++) { Integer frontImage =inageList.get(i).getFrontImage(); String imgName = ""; if(1==frontImage){ //首圖 imgName = "首圖"+i; this.downloadPicture(inageList.get(i).getImageUrl(), courseFile,imgName); }else{ // imgName = "內容圖"+i; this.downloadPicture(inageList.get(i).getImageUrl(), courseFile,imgName); } } StringBuffer buffer = new StringBuffer(); buffer.append("產品名:"+title+"\r\n"); buffer.append("可用星期可用天數 :"+this.strToWeek(validWeekRule)+"\r\n"); //將解析的文字記錄到txt FileMT.saveFile(fileName, buffer.toString(),courseFile); //壓縮文件 courseFile FileOutputStream fos1 = new FileOutputStream(new File(courseFile+".zip")); ZipUtils.toZip(courseFile, fos1, false); returnMap.put("url", courseFile);//返回生成的文件夾名稱和路徑 returnMap.put("name", fileName); return returnMap; }
用到的公共方法:在解析周的時候,做了特殊處理,因為產品信息返回的周例如:"1101000"表示周一周二和周四可用,所以我們給用戶展現需要轉換過來。
一下是用到了方法:1101000轉換星期
public static String strToWeek(String str){ String week=""; String[] weekArr={"星期一","星期二","星期三","星期四","星期五","星期六","星期日"}; for(int i=0;i<str.length();i++){ String curStr=str.substring(i, i+1); if("1".equals(curStr)){ week+=weekArr[i]+","; } } if(StringUtils.isNotBlank(week)){ week=week.substring(0,week.length()-1); } return week; }
下載網絡圖片:
/*** *urlList == 網絡路徑;path===下載存放的位置;imgName==圖片名稱 **/ private static void downloadPicture(String urlList,String path,String imgName) { URL url = null; try { url = new URL(urlList); DataInputStream dataInputStream = new DataInputStream(url.openStream()); FileOutputStream fileOutputStream = new FileOutputStream(new File(path+"\\"+imgName+".jpg")); ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = dataInputStream.read(buffer)) > 0) { output.write(buffer, 0, length); } fileOutputStream.write(output.toByteArray()); dataInputStream.close(); fileOutputStream.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
FileMT類,保存成txt文本。
public static String saveFile(String fileName,String content,String url){ String result=""; try { contentToTxt(url+"/"+fileName+".txt", content); result="1"; } catch (Exception e) { result="2"; e.printStackTrace(); } return result; } public static void contentToTxt(String filePath, String content) { String str = new String(); String s1 = new String(); try { File f = new File(filePath); File parent = f.getParentFile(); if(parent!=null&&!parent.exists()){ parent.mkdirs(); } f.createNewFile(); if (f.exists()) { System.out.print("文件存在"); } else { System.out.print("文件不存在"); f.createNewFile(); } BufferedReader input = new BufferedReader(new FileReader(f)); while ((str = input.readLine()) != null) { s1 +=""; } input.close(); content= new String(content.getBytes("UTF-8"),"UTF-8"); s1 += content; BufferedWriter output = new BufferedWriter(new FileWriterWithEncoding(f, "utf-8")); output.write(s1); output.close(); } catch (Exception e) { e.printStackTrace(); } }
ZipUtils類,主要是壓縮文件和刪除文件夾工具類:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import com.tmwsoft.util.EncryptPassword;
public class ZipUtils {
private static final int BUFFER_SIZE = 2 * 1024;
/**
* 壓縮成ZIP 方法1
*
* @param srcDir
* 壓縮文件夾路徑
* @param out
* 壓縮文件輸出流
* @param KeepDirStructure
* 是否保留原來的目錄結構,true:保留目錄結構;
* false:所有文件跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名文件,會壓縮失敗)
* @throws RuntimeException
* 壓縮失敗會拋出運行時異常
*/
public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
long end = System.currentTimeMillis();
System.out.println("壓縮完成,耗時:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 遞歸壓縮方法
*
* @param sourceFile
* 源文件
* @param zos
* zip輸出流
* @param name
* 壓縮后的名稱
* @param KeepDirStructure
* 是否保留原來的目錄結構,true:保留目錄結構;
* false:所有文件跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名文件,會壓縮失敗)
* @throws Exception
*/
private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure)
throws Exception {
byte[] buf = new byte[BUFFER_SIZE];
if (sourceFile.isFile()) {
// 向zip輸出流中添加一個zip實體,構造器中name為zip實體的文件的名字
zos.putNextEntry(new ZipEntry(name));
// copy文件到zip輸出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
// Complete the entry
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if (listFiles == null || listFiles.length == 0) {
// 需要保留原來的文件結構時,需要對空文件夾進行處理
if (KeepDirStructure) {
// 空文件夾的處理
zos.putNextEntry(new ZipEntry(name + "/"));
// 沒有文件,不需要文件的copy
zos.closeEntry();
}
} else {
for (File file : listFiles) {
// 判斷是否需要保留原來的文件結構
if (KeepDirStructure) {
// 注意:file.getName()前面需要帶上父文件夾的名字加一斜杠,
// 不然最后壓縮包中就不能保留原來的文件結構,即:所有文件都跑到壓縮包根目錄下了
compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
} else {
compress(file, zos, file.getName(), KeepDirStructure);
}
}
}
}
}
public static boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);// 先刪除文件夾里面的文件
delFolder(path + "/" + tempList[i]);// 再刪除空文件夾
flag = true;
}
}
return flag;
}
public static void delFolder(String folderPath) {
try {
delAllFile(folderPath); // 刪除完里面所有內容
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
myFilePath.delete(); // 刪除空文件夾
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws FileNotFoundException {
/** 測試壓縮方法1 */
FileOutputStream fos1 = new FileOutputStream(new File("f:/新建文本文檔.zip"));
ZipUtils.toZip("f:/新建文本文檔.txt", fos1, true);
}
}
最后來個聲明,以上所有資料都是我在網上找的別人的文章,然后復制代碼變成我的了,已經找不到具體哪一篇。
