Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty folder is created in 7Zip while compressing file in java

Tags:

java

7zip

I am using Java compression API (java.util.ZIP package) to compress the files. It works well. However, I have below small issue.

Suppose my input file is C:\temp\text.txt and my output (compressed) file is C:\temp\text.zip

When I view the compressed file (text.zip) using WinZip it is shown correctly with the inner folder structure. It is shown as temp\text.txt. But if the same file is opened with 7Zip (using right click -> 7Zip -> Open archive option) it shows an empty folder after C:\temp\text.zip\. To view the text.txt I need to enter C:\temp\text.zip\\\temp\ in 7Zip address bar. Notice the double backslash \\\ here.

Below is my code:

String input="C:\temp\text.txt";
String output="C:\temp\text.zip";
FileOutputStream dest = new FileOutputStream(output);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
out.setMethod(ZipOutputStream.DEFLATED); //Entries can be added to a ZIP file in a compressed (DEFLATED) form 
out.setLevel(this.getZIPLevel(Deflater.DEFAULT_COMPRESSION));

File file = new File(input);
final int BUFFER = 2048;
byte data[] = new byte[BUFFER];
BufferedInputStream origin = null;
FileInputStream fi;

fi = new FileInputStream(file);
origin = new BufferedInputStream(fi, BUFFER);

int index = file.getAbsolutePath().indexOf(":") + 1;
String relativePath = file.getPath().substring(index);

ZipEntry entry = new ZipEntry(relativePath);
out.putNextEntry(entry);
int count;
while((count = origin.read(data, 0, BUFFER)) != -1) {
      out.write(data, 0, count);
}
origin.close();
out.close();

Can someone tell me why I see additional empty folder using 7Zip? I am using JDK7.

like image 376
ParagJ Avatar asked Dec 04 '25 16:12

ParagJ


1 Answers

For starters, try fixing this:

String input = "C:\\temp\\text.txt";
String output = "C:\\temp\\text.zip";

Notice that you need to escape the \ char in a String. Given that "\t" is a valid escape sequence it might have worked before, but with a couple of tab characters thrown in the middle of the name. To avoid the need to escape the path separator you can write it like this:

String input = "C:/temp/text.txt";
String output = "C:/temp/text.zip";

And to make it a bit more portable, you can replace both "\\" and "/" with File.separator, a constant which holds the correct system-dependent name-separator for your environment (the "C:" part won't be portable, though.)

like image 172
Óscar López Avatar answered Dec 06 '25 04:12

Óscar López