Logan
Logan

Reputation: 2505

Problem in Zipping a File

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();
        }
    }

}

Upvotes: 0

Views: 506

Answers (1)

dogbane
dogbane

Reputation: 274612

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.

Upvotes: 3

Related Questions