How to unzip a zip file with java

I was writing a script in java, to download the some files from a webserver, then open them and read then, and insert some files into the database.

What i noticed was that. when i downloaded the files with my browser, everything was ok, but when i downloaded then with the java program the files weren’t saved as text but something else, binary.

At first I thought that it was some kind of protection, so i changed the user agent of my script to that of firefox, and the refferer (some times some web developers have protection for these things) but again no good results.

Then i thought that maybe, the webserver ignored my AcceptEncoding header and sent the file in gzip format anyway. Then I searched the web for some function to unzip a file with java, I tried it and it worked.

The link is this for anyone interested: http://www.roseindia.net/java/beginners/JavaUncompress.shtml.

I will write a full file download function that takes into account the encoding header and unzips the file if nessesarry.

I will post it here when it’s done.

 

Ok this is the method, it isn’t pretty but it works:

Includes:

import java.util.*;
import java.net.*;
import java.io.*;
import java.util.regex.*;
import java.sql.*;
import java.util.regex.*;
import java.nio.channels.*;
import java.util.zip.GZIPInputStream;

Actual Code:

	static void download2(String u, String filename)
	{
		try
		{
		    URL url = new URL(u);
		    URLConnection con = url.openConnection();
		    con.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1");
		    ReadableByteChannel rbc = Channels.newChannel(url.openStream());
		    FileOutputStream fos = new FileOutputStream(filename);
		    fos.getChannel().transferFrom(rbc, 0, 1 << 24);
		    String inFilename = filename;
		    GZIPInputStream gzipInputStream = null;
      		FileInputStream fileInputStream = null;
			fos.close();
 
      	   if (con.getContentEncoding()!= null && con.getContentEncoding().equals("gzip"))
      	    {
 
 
      	    	//unzip it
	      	    gzipInputStream = new GZIPInputStream(new FileInputStream(inFilename));
	      	    String outFilename = inFilename+".temp";
	      	    new File(filename).delete();
      	  	    OutputStream out2 = new FileOutputStream(outFilename);
      	        byte[] buf = new byte[1024];
      	        int len;
                while ((len = gzipInputStream.read(buf)) > 0) 
                {
                	out2.write(buf, 0, len);
                }
 
       			gzipInputStream.close();
                out2.close();
                new File(filename).delete();
                new File(outFilename).renameTo(new File(filename));    	
      	    }
 
 
 
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}