Java util zip creates “corrupt” zip files

I zip up the contents of the directory, but I get an error when I try to open archived files.

Can anyone tell what is happening with my code? Perhaps I do not allocate enough bytes?

Take a peek inside zipDirectory () and you will see that I zip folders containing special extension files.

I don’t know where the error is, so maybe someone can help me!

Very much appreciated

private void zipDirectory() { File lazyDirectory = new File(defaultSaveLocation); File[] files = lazyDirectory.listFiles(); for (File file : files) { if (file.isDirectory()) { System.out.println("Zipping up " + file); zipContents(file); } } } public static void addToZip(String fileName, ZipOutputStream zos) throws FileNotFoundException, IOException { System.out.println("Writing '" + fileName + "' to zip file"); File file = new File(fileName); FileInputStream fis = new FileInputStream(file); ZipEntry zipEntry = new ZipEntry(fileName); zos.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zos.write(bytes, 0, length); } zos.closeEntry(); fis.close(); } public static void zipContents(File dirToZip) { List<File> fileList = new ArrayList<File>(); File[] filesToZip = dirToZip.listFiles(); for (File zipThis : filesToZip) { String ext = ""; int i = zipThis.toString().lastIndexOf('.'); if (i > 0) { ext = zipThis.toString().substring(i+1); } if(ext.matches("cpp|bem|gz|h|hpp|pl|pln|ppcout|vec|xml|csv")){ fileList.add(zipThis); } } try { FileOutputStream fos = new FileOutputStream(dirToZip.getName() + ".zip"); ZipOutputStream zos = new ZipOutputStream(fos); for (File file : fileList) { addToZip(file.toString(), zos); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } 

enter image description here

+6
source share
3 answers

Like most problems with input / output streams in Java, your error almost certainly is that you are not closing the threads properly. You need to add:

 zos.finish(); // good practice zos.close(); 

after the for loop.

+14
source

For me it’s fixed that you need to do this for recording EVERY

 zos.finish() zos.flush() zos.closeEntry() 

Then repeat the above steps to close zos . Otherwise, the default windows will not be able to open the mail folder correctly, but a third-party application works.

0
source

This can also happen if you use a character-oriented writer (e.g. FileWriter) to create decompressed files (which actually contain binary data)

I was unable to read the files I was extracting and switching to binary output stream (FileOutputStream) fixed the problem

0
source

Source: https://habr.com/ru/post/947059/


All Articles