0

When I run my code and use the files that are in the resource folder of my project itself, I face no problems. It zips the file successfully and I can extract it using WINZIP. The problem comes when I try to zip a file that is not in the project folder.

When I do the same, I am passing the Absolute Path of both the src and the dest files. My program doesn't give any exceptions, but when I try to open that zip file, I get an error saying, File is Invalid.

Can anyone tell me why this may be happening.

public static void compress(String srcPath, String destPath) {

    srcFile = new File(srcPath);
    destFile = new File(destPath);
    try {
        fileInputStream = new FileInputStream(srcFile);
        fileOutputStream = new FileOutputStream(destFile);
        zipEntry = new ZipEntry(srcPath);
        zipOutputStream = new ZipOutputStream(fileOutputStream);
        zipOutputStream.putNextEntry(zipEntry);
        byte[] data = new byte[12];
        while ((fileInputStream.read(data)) != -1) {
            zipOutputStream.write(data);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try{
            fileInputStream.close();
        zipOutputStream.close();}catch (Exception e) {
            e.printStackTrace();
        }
    }

}
4
  • 2
    Which API? Code snippet?
    – Wivani
    Aug 9, 2011 at 12:26
  • Is this on Windows? Are you creating zip entries with drive letters e.g. C:\path\file.txt?
    – dogbane
    Aug 9, 2011 at 12:29
  • @dogbane: Yes, it is windows and I am creating zip entries with drive letters.
    – Logan
    Aug 9, 2011 at 12:30
  • @Wivani: I am using java.util.zip.* .
    – Logan
    Aug 9, 2011 at 12:31

1 Answer 1

3

You should not store paths with drive letters in your zip file because when you try to extract your zip, it will try to create a directory with the name of the drive and fail.

You will need to change your code so that it removes the drive letter from the path before creating the ZipEntry.

3
  • Thanks, it worked. But why we have to remove the Drive Letter from the Path?
    – Logan
    Aug 9, 2011 at 13:00
  • Try creating a directory called "C:". You will see that it is not allowed. In the same way, if you had drive letters in your zip and tried to extract it, it would fail.
    – dogbane
    Aug 9, 2011 at 13:05
  • Yes, its failing. But if I use 7zip to extract the file, its not failing. Instead, in the decompressed folder I see folders like D_ and then all inner folders.
    – Logan
    Aug 9, 2011 at 13:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.