Android: download and decompress GZIP file on the fly

Code snippet below shows a neat way of downloading and decompressing a GZIP file on the fly. This saves from having to programmatically download the file first and then decompressing it. I have used this for downloading and unzipping a GZIP file that contained an XML document.

protected String doInBackground(String... sUrl) {
	try {
		URL url = new URL(sUrl[0]);
		URLConnection connection = url.openConnection();
		InputStream stream = connection.getInputStream();
		stream = new GZIPInputStream(stream);
		InputSource is = new InputSource(stream);
		InputStream input = new BufferedInputStream(is.getByteStream());
		OutputStream output = new FileOutputStream("Path to the file");
		byte data[] = new byte[2097152];
		long total = 0;
		int count;
		
		while ((count = input.read(data)) != -1) {
			total += count;
			output.write(data, 0, count);
		}

		output.flush();
		output.close();
		input.close();
	} catch (BufferOverflowException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
		return null;
	}
}
Advertisement