I am writing a Java archiver. I collected the files in a Zip archive, but if you open it through Windows Explorer, it looks as if it is empty (no files are displayed). And you need the user to open and see that he has 5 files in the archive and a picture.

And if you unpack the JAVA code with this seemingly empty archive, then there really will be data.
What parameter should be set for compression, what is the solution?

//zip to test.zip public static void main(String[] args) throws IOException { File archive = new File("test.zip"); if (!archive.exists()) { archive.createNewFile(); } List<String> files = new ArrayList<>(); files.add(PATH_TO_FILE1); files.add(PATH_TO_FILE2); ZipOutputStream zip = new ZipOutputStream(new CheckedOutputStream(new FileOutputStream(archive), new CRC32())); BufferedOutputStream writer = new BufferedOutputStream(zip); for (String datFile : files) { BufferedReader reader = new BufferedReader(new FileReader(datFile)); zip.putNextEntry(new ZipEntry(datFile)); int c; while ((c = reader.read()) != -1) { writer.write(c); } writer.flush(); reader.close(); } writer.flush(); writer.close(); //Unzip ZipInputStream zipInputStream = new ZipInputStream(new CheckedInputStream(new FileInputStream(archive), new CRC32())); BufferedInputStream bufferedInputStream = new BufferedInputStream(zipInputStream); ZipEntry entry; while ((entry = zipInputStream.getNextEntry()) != null) { System.out.println("Reading file " + entry); int c; while ((c = bufferedInputStream.read()) != -1) { System.out.print((char) c); } System.out.println(); } zipInputStream.close(); 
  • 2
    And what's the problem? - Roman
  • I will assume that the problem is in using the full path to the files, because of this, the colon that the explorer does not understand gets into ZipEntry . You also need to use *InputStream instead of *Reader to read files - zRrr

1 answer 1

In addition to putNextEntry() you also need to call closeEntry() :

 for (String datFile : files) { BufferedReader reader = new BufferedReader(new FileReader(datFile)); zip.putNextEntry(new ZipEntry(datFile)); int c; while ((c = reader.read()) != -1) { writer.write(c); } writer.flush(); reader.close(); zip.closeEntry(); } 

PS And usually ZipOutputStream wraps the BufferedOutputStream , and not vice versa.