I want to read the last n lines of a big txt file compressed in a zip file without unzipping it.
This is what I have now:
ZipFile zf = new ZipFile(file.getAbsolutePath());
Enumeration<?> entries = zf.entries();
ZipEntry ze = (ZipEntry) entries.nextElement();
BufferedReader in = new BufferedReader(new InputStreamReader(zf.getInputStream(ze)));
void readLastNLines(BufferedReader bf){
//some code here
}
I was thinking of the way using RandomAccessFile(File file, String mode)
but it requires a File
as the argument. Zip file cannot be treated like directory so I cannot pass it.
Any ideas?
Appreciate any assistance and inputs.
Thanks!
[EDIT] I figure out a less efficient way to achieve this:
Since RandomAccessFile
cannot be used, I used the InputStream
approach:
InputStream is = zf.getInputStream(ze);
int length = is.available();
byte[] bytes = new byte[length];
int ch = -1;
while ((ch = is.read()) != -1) {
bytes[--length] = (byte) ch;
}
String line = new String(bytes);
//reverse the string
String newLine = new StringBuilder(line).reverse().toString();
//Select how many lines do you want(some number = number of bytes)
System.out.println(newLine.substring(line.length()-#some number#));