Liam Haworth
Liam Haworth

Reputation: 858

Java - Zip to file dir issue

I'm still working on the same app from the other question, I was going fine till I started to work on the ZipExtractToFile void, code works fine with the files in the root of the zip but fails with dir, here's the output from the console:

Exception in thread "main" java.io.FileNotFoundException: minecraft\achievement\bg.png (The system cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at com.hachisoftware.mmi.system.Util.ZipExtractToFile(Util.java:56)
at com.hachisoftware.mmi.MinecraftModInstaller.startSystem(MinecraftModInstaller.java:51)
at com.hachisoftware.mmi.MinecraftModInstaller.main(MinecraftModInstaller.java:27)

and here is the code:

public static void ZipExtractToFile(File inZip, File outDir) throws IOException
{
    ZipInputStream zis = new ZipInputStream(new FileInputStream(inZip));
    if(!outDir.exists())
    {
        outDir.mkdir();
    }
    byte[] buffer = new byte[1024];

    for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) 
    {
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outDir + "\\" + ze.getName())));

        if(ze.isDirectory())
        {
            File dir = new File(ze.getName());
            dir.mkdir();
            continue;
        }

        for (int read = zis.read(buffer); read != -1; read = zis.read(buffer)) {
            out.write(buffer, 0, read);
        }
        out.flush();
        out.close();
    }

    zis.close();
}

The error is at:

BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outDir + "\\" + ze.getName())));

Upvotes: 0

Views: 334

Answers (1)

darioo
darioo

Reputation: 47183

First of all, you are using this line prematurely:

BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outDir + "\\" + ze.getName())));

This will throw an exception since FileOutputStream expects a file, not a directory, and at this stage you are not sure if outDir + "\\" + ze.getName() is a file or not.

You should put that line after

if(ze.isDirectory()) {...}

Secondly, if you know that you're creating a new directory, or a file, and you know its parent; it would be better to use this constructor:

public File(File parent, String child)

See the relevant Javadoc.

Using code like outDir + "\\" + ze.getName() is more likely to cause errors if you're not careful.

Upvotes: 2

Related Questions