Here’s a code snippet demonstrating how to download a zip file and extract the files contained within.
The variable zip_url_string represents the URL to download the zip file from. To read in each file, put your code after the BufferedReader statement.
/**
* Our first task is to grab the file, and open up a ZipInputStream to decompress the file.
* A ZipEntry processes each entry within the ZipInputStream.
*/
URL url_addr = new URL(zip_url_string);
HttpURLConnection con = (HttpURLConnection)url_addr.openConnection();
InputStream fis = con.getInputStream();
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry entry = zis.getNextEntry();
/**
* We are going to loop through each ZipEntry until we get to a null entry (which
* represents the end of the ZipEntry list within the ZipInputStream).
**/
while (entry != null) {
//Collect the entry name. This is the filename, including any directory information.
//Do any validation or processing needed.
String entry_name = entry.getName().trim();
//Create a BufferedReader to read in the contents of this file contained within the zip.
InputStreamReader isr = new InputStreamReader(zis);
BufferedReader reader = new BufferedReader(isr);
/**
* Do something here with the file. Use BufferedReader to read it in, then
* process it as necessary.
*/
//Grab the next entry for processing
entry = zis.getNextEntry();
}//end while loop going through ZipEntry entries
If the zip file being downloaded is especially large, you may want to add a longer timeout:
con.setConnectTimeout(milliseconds_to_wait);
Remember to add the appropriate import statements:
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.InputStream;
import java.util.zip.*;