將多個檔案打包到一個壓縮包裡面
阿新 • • 發佈:2020-09-14
public byte[] zip(List<String> fileNameList,List<String> filePathList) throws IOException { List<byte[]> listBytes = new ArrayList<>(); for (String downPath :filePathList) { //從主機獲得檔案流 InputStream is =new FileInputStream(downPath); byte[] down = IOUtils.toByteArray(is); listBytes.add(down); is.close(); } ByteArrayOutputStream fileOutputStream= new ByteArrayOutputStream(); ZipOutputStream out = new ZipOutputStream(fileOutputStream); ZipEntry entry = null; for (int i = 0; i < fileNameList.size(); i++) { byte[] tmpBytes = listBytes.get(i); String name = fileNameList.get(i); entry = new ZipEntry(name);// 儲存項資訊到壓縮檔案 out.putNextEntry(entry); // 將檔案的內容通過位元組陣列複製到壓縮檔案中 out.write(tmpBytes, 0, tmpBytes.length); out.closeEntry(); } out.close(); out.flush(); fileOutputStream.close(); byte[] bytes = fileOutputStream.toByteArray(); return bytes; }