java使用 zipoutputstream 進行解壓縮時提示:不可預料的壓縮檔案末端
阿新 • • 發佈:2018-11-09
private static void zip(File filein, String basepath, ZipOutputStream out) throws IOException { FileInputStream in = null; try { if (filein.isDirectory()) { File files[] = filein.listFiles(); /*if (basepath != "") { out.putNextEntry(new ZipEntry(basepath + File.separator)); } basepath = basepath.length() == 0 ? "" : basepath +File.separator;*/ for (int i = 0; i < files.length; i++) { zip(files[i], basepath+File.separator+files[i].getName(), out); } } else { out.putNextEntry(new ZipEntry(basepath)); in= new FileInputStream(filein); int a = 0; while ((a = in.read()) != -1) { out.write(a); } } } catch (Exception e) { e.printStackTrace(); }finally { if (in != null) { in.close(); } }
我出現這個錯誤的原因是沒有執行 zipput.close()將輸出流關閉,導致 壓縮出來的檔案有問題
File file = new File("D:\\test");
ZipOutputStream zipout = new ZipOutputStream(
new FileOutputStream(new File("D:" + File.separator + "test.zip")));
zip(file, file.getName(), zipout);
zipout.close();