4

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
}
BJ Dela Cruz
  • 5,194
  • 13
  • 51
  • 84

3 Answers3

2

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
Durandal
  • 5,575
  • 5
  • 35
  • 49
  • In Android, would the file path be `/res/raw/file.zip` assuming that I put `file.zip` in the `/res/raw` directory? – BJ Dela Cruz Mar 01 '14 at 03:19
  • dont' think it's that simple in android sadly: think this answer is what you'll need to do: http://stackoverflow.com/a/2017641/772385 , also some strange rules for file names as specified here: http://stackoverflow.com/a/15934525/772385 – Durandal Mar 01 '14 at 03:31
1

I found what I needed here. The person who answered the question recommended using the read method in ZipInputStream and reading the contents of the entries into a StringBuffer.

Community
  • 1
  • 1
BJ Dela Cruz
  • 5,194
  • 13
  • 51
  • 84
0

Try something like this:

public static void unzip(File zipFile) throws IOException {

    byte[] buff = new byte[1024];
    ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
    ZipEntry ze;

    while ((ze = zis.getNextEntry()) != null) {
        if (!ze.isDirectory()) {                
            while (zin.read(buff) >= 0)
                // Do something with buff

        zis.closeEntry();
    }

    zis.close();
}
scottt
  • 8,301
  • 1
  • 31
  • 41