Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a zip file and iterate through each compressed file on Android?

Tags:

java

android

zip

I have a zip file in my res/raw directory. I want to open the zip file and iterate through the text files that are stored in it. I do not want to extract and write the files to the device; I just want to open the zip file, iterate through the lines in each text file, and then close the zip file.

I'm having trouble trying to read in the zip file because the openRawResource method returns an InputStream. I tried to convert the stream to a ZipInputStream, but I'm lost as to what to do next.

How do I create a ZipFile object in this case?

It's not much, but here's what I have so far:

InputStream in = getResources().openRawResource(R.raw.primes);
ZipInputStream zin = new ZipInputStream(in);
ZipEntry entry;
while ((entry = zin.getNextEntry()) != null) {
  // TODO
}
like image 991
BJ Dela Cruz Avatar asked Oct 21 '25 10:10

BJ Dela Cruz


1 Answers

You can create a ZipFile with just a path and then put each entry into a BufferedReader using the ZipInputStream like this:

    ZipFile zipFile = new ZipFile("file_path");
    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    while(entries.hasMoreElements()) {
        ZipEntry zipEntry = entries.nextElement();
        System.out.println(zipEntry.getName());
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry)));
        String line;
        while((line = bufferedReader.readLine()) != null){
            System.out.println(line);
        }
        bufferedReader.close();
    }
    zipFile.close();
}

To get the file in res/raw you'll have to do something like this:

getResources().getIdentifier("myfile","raw", getPackageName()); //for res/raw/myfile.zip
like image 144
Durandal Avatar answered Oct 23 '25 23:10

Durandal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!