0

I want to read first line of a file inside a zip file. Now I do it using while loop like this one sample stackoverflow quesion link

But I know the exact location of file inside that zip. And the zip file is very big(can be more than 500mb).

So I'm thinking is there a way to read that file without looping through all files using while.

Community
  • 1
  • 1
Shirish Herwade
  • 11,461
  • 20
  • 72
  • 111

1 Answers1

0

Use ZipFile instead of ZipInputStream. This reads the zip file's central directory (see Wikipedia article) and not the whole file. You can then use entries() or getEntry(java.lang.String) and getInputStream(java.util.zip.ZipEntry) to get an input stream for the entry:

String entryName = // put name of your entry here
File file = // put your zip file here
ZipFile zipFile = null;
try {
    zipFile = ZipFile(file);
    ZipEntry zipEntry = zipFile.getEntry(entryName);
    InputStream is = null;
    try {
        is = zipFile.getInputStream(zipEntry);
        // read stream here e.g. using BufferedReader
    } catch (IOException ex) {
        // TODO: handle exception or delete catch block
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ex) {
            }
        }
    }
} finally {
    if (zipFile != null) {
        zipFile.close();
    }
}
fabian
  • 80,457
  • 12
  • 86
  • 114