Click here to Skip to main content
13,049,263 members (68,112 online)
Click here to Skip to main content
Add your own
alternative version

Stats

112.4K views
23 bookmarked
Posted 8 May 2004

Bug when using the java.util.zip classes to write zip files

, 8 May 2004
Rate this:
Please Sign up or sign in to vote.
Describes an issue when writing a binary file into a zip file using the java.util.zip classes

Introduction

I was writing a little .NET app in C# and was looking for a small library that would let me read and write zip files. That's when my first Google search gave me a link to Using the Zip Classes in the J# Class Libraries to Compress Files and Data with C#. Great! - that was my first reaction, but it didn't last too long. You can read zip files alright, but when you write zip files, if you have binary files (as you most often will), the generated zip file will be corrupt and you can't read it back. Funnily, WinZip does open it (ignoring the header errors) and the suggested solution by a Microsoftie in the one of the MS NGs was to extract all files using WinZip and then to zip it back. LOL. Why'd anyone want to use the zipping libraries at all if they had the option of bringing WinZip into the picture?

There is not even a KB article on this bug - bad! I lost about half a day when I was using these classes because I initially thought it was something wrong in my code. Anyway, this is a warning to everyone. Do not use the J# class libraries for zipping/unzipping if you are using the BCL 1.1 version. Heath Stewart (C# MVP and CodeProject Editor) has informed me that the BCL 2.0 includes zipping functionality - so that's really good news. And until that comes out, a very good free alternative to the J# classes is SharpZipLib which I very strongly recommend.

Bug demo

  1. Create a new C# console app project
  2. Add a reference to vjslib (...Microsoft.NET\Framework\v1.1.4322\vjslib.dll)
  3. Copy/paste the following code into your main cs file :-
    using System;
    using System.IO;
    using java.util.zip;
    
    class MainClass
    {
      [STAThread]
      static void Main(string[] args)
      {
        BugDemo();
      }
    
      static void BugDemo()
      {
        //Write zip file
        ZipOutputStream os = new ZipOutputStream(
          new java.io.FileOutputStream("test.zip"));
        ZipEntry ze = new ZipEntry("gluk.gif");
        ze.setMethod(ZipEntry.DEFLATED);
        os.putNextEntry(ze);
        java.io.FileInputStream fs = 
          new java.io.FileInputStream("gluk.gif");
        sbyte[] buff = new sbyte[1024];
        int n = 0;
    
        while ((n=fs.read(buff,0,buff.Length))>0)
        {
          os.write(buff,0,n);
        }
        fs.close();
        os.closeEntry();      
        os.close();
    
        Console.WriteLine("Okay, the zip has been written.");
    
        //Read zip file
        try
        {
          //Bug will occur here
          ZipFile zf = new ZipFile("test.zip");  
        }
        catch
        {
          Console.WriteLine("Bug confirmed!");
        }
      }
    }
  4. Now make sure you have a gluk.gif in the same folder as the executable.

  5. Compile and run.

Workaround

There is no real workaround to the problem. You can use the alternative library I mentioned above or wait for Whidbey.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Nish Nishant
United States United States
Nish Nishant is the Principal Software Architect/Consultant for Ganymede Software Solutions LLC, and is based out of Columbus, Ohio. He has over 17 years of software industry experience in various roles including Lead Software Architect, Principal Software Engineer, and Product Manager. Nish was a Microsoft Visual C++ MVP between 2002 and 2015.

Nish is an industry acknowledged expert in the Microsoft technology stack. He authored C++/CLI in Action for Manning Publications in 2005, and had previously co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his WordPress blog. Nish is vastly experienced in team management, mentoring teams, and directing all stages of software development.

Contact Nish : If you are interested in hiring Nish as a consultant, you can reach him via his google email id voidnish.

Company Website : www.ganymedesoftwaresolutions.com

You may also be interested in...

Pro

Comments and Discussions

 
Questionhow to open and read files from a zip file using jsp or java Pin
sandhyamn8-Jun-07 19:56
membersandhyamn8-Jun-07 19:56 
GeneralJava Zip Pin
SanjitP11-Apr-07 22:28
memberSanjitP11-Apr-07 22:28 
GeneralRe: Java Zip Pin
WajeehAhmed16-Apr-07 1:30
memberWajeehAhmed16-Apr-07 1:30 
QuestionAlternative? Pin
evoluzion22-Dec-06 11:02
memberevoluzion22-Dec-06 11:02 
AnswerRe: Alternative? Pin
Brad Bruce22-Dec-06 11:19
memberBrad Bruce22-Dec-06 11:19 
GeneralVB convert procedure Pin
Alessandro Betti17-May-06 6:56
memberAlessandro Betti17-May-06 6:56 
Generalon text files Pin
dvsr27-Dec-05 13:33
memberdvsr27-Dec-05 13:33 
GeneralAlternative (with code) Pin
Elmue17-Nov-05 2:30
memberElmue17-Nov-05 2:30 
Hello

As vjslib is buggy (don't use it) try this one:
http://www.icsharpcode.net/OpenSource/SharpZipLib/

There are 3 advantages over vjslib:
1.) It works without bugs.
2.) It also supports GZip, Tar and BZip2 .
3.) The DLL you need is only 140 kB instead of 3,7 MB.

The SharpZipLib has a good detailed documentation but it lacks examples.
So I post my code here which I use to zip a whole folder into a ZIP file.

Elmü

using ICSharpCode.SharpZipLib.Zip;
 
/// <summary>
/// Packs a folder and all files in all its subfolders into a ZIP file preserving the relative paths
/// Requires ICSharpCode.SharpZipLib library
/// http://www.icsharpcode.net/OpenSource/SharpZipLib
/// </summary>
static public void PackFolderIntoZipFile(string s_Folder, string s_ZipFile)
{
	ZipOutputStream i_zStream = new ZipOutputStream(File.Create(s_ZipFile));
	i_zStream.SetLevel(5); // Compression level (0-9)
 
	int s32_BaseFolderLen = s_Folder.Length;
	if (s_Folder.Substring(s_Folder.Length-1) != "\\") s32_BaseFolderLen ++;
 
	ArrayList i_FileList = new ArrayList();
	EnumFiles(ref i_FileList, s_Folder, "*.*", true);
 
	Byte[] u8_Buf = new Byte[0x100000]; // 1 Megabyte buffer
 
	foreach (string s_File in i_FileList)
	{
		FileStream i_fStream = null;
		// Catch errors of files which are locked (cannot be opened)
		try   { i_fStream = File.OpenRead(s_File); }
		catch { continue; }
 
		// Cut the base folder ("E:\ZipFolder\Subfolder\File.txt" -> "Subfolder/File.txt")
		// The zip archive requires "/" as separator
		string s_ZipPath = s_File.Substring(s32_BaseFolderLen).Replace("\\", "/");
 
		ZipEntry i_ZipEntr = new ZipEntry(s_ZipPath);
		FileInfo i_Info    = new FileInfo(s_File);
		i_ZipEntr.DateTime = i_Info.LastWriteTime;
		i_zStream.PutNextEntry(i_ZipEntr);
 
		while (true)
		{
			int s32_Len = i_fStream.Read(u8_Buf, 0, u8_Buf.Length);
			if (s32_Len <= 0)
				break;
			
			i_zStream.Write(u8_Buf, 0, s32_Len);
		}
 
		i_fStream.Close();
	}
 
	i_zStream.Finish();
	i_zStream.Close();
}
 
/// <summary>
/// This recursive function searches all files in the given folder and its subfolders
/// s_Filter = "*.Extension"
/// s_Path   = Start path
/// </summary>
static public void EnumFiles(ref ArrayList i_FileList, string s_Path, string s_Filter, bool b_Subfolders)
{
	if (s_Path == null || s_Path == "")
		return;
 
	string[] s_Files = Directory.GetFiles(s_Path, s_Filter.Trim());
	foreach (string s_File in s_Files)
	{
		i_FileList.Add(s_File);
	}
 
	if (b_Subfolders)
	{
		string[] s_Dirs = Directory.GetDirectories(s_Path);
		foreach (string s_Dir in s_Dirs)
		{
			EnumFiles(ref i_FileList, s_Dir, s_Filter, true);
		}
	}
}

GeneralA fix available from M$ Pin
rshearer31-Aug-05 10:43
memberrshearer31-Aug-05 10:43 
GeneralAnother big problem Pin
nahumtakum15-May-04 0:31
membernahumtakum15-May-04 0:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 9 May 2004
Article Copyright 2004 by Nish Nishant
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid