FileOutputStream throws FileNotFoundException when UnZipping

前端 未结 7 1786
温柔的废话
温柔的废话 2020-12-11 04:19

I\'m using a class that I found through google to unzip a .zip file.. The .zip contains files and folder. The problem is that FileOutputStream throws

7条回答
  •  长情又很酷
    2020-12-11 04:50

    The problem here is caused due to zip files or directories nested within the given zip. In case the given ZipEntry is a directory, you need to create the directory and skip writing with the FileOutputStream.

    use zipEnrty.isDirectory() to check whether the given zipEntry is a directory and create the directory using zipEntry.mkDirs() and proceed to the next zipEntry without writing it using fileOutputStream.

    Here is the full code for unzipping a zip file :

    import java.io.*;
    import java.util.zip.*;
    
    public class Unzip
    {
        public static void main (String args[])
        {
            try
            {
                final int BUFFER = 1024;
                int count;
                byte data[] = new byte[BUFFER];
                String path="res/Example.zip";
    
                BufferedOutputStream bufferedOutputStream = null;
                FileInputStream fileInputStream = new FileInputStream(path);
                ZipInputStream zipInputStream = new ZipInputStream(new  BufferedInputStream(fileInputStream));
                ZipEntry zipEntry;
    
                while((zipEntry = zipInputStream.getNextEntry()) != null)
                {
                    System.out.println("Extracting: " +zipEntry);
                    File file=new File(zipEntry.getName());
                    if(zipEntry.isDirectory())
                    {
                        file.mkdirs();
                        continue;
                    }
                    FileOutputStream fileOutputStream = new     FileOutputStream(file,false);
                    bufferedOutputStream = new BufferedOutputStream(fileOutputStream, BUFFER);
    
                    while ((count = zipInputStream.read(data, 0, BUFFER))!= -1)
                    bufferedOutputStream.write(data, 0, count);
    
                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                }
                zipInputStream.close();
            } 
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    

提交回复
热议问题