I have a data file that has a header, say 0x270 bytes. Beyond that header, there is a zip file. How can I skip the header part and copy the content of the zip file in a new file?
I am considering trying this, but I am unsure if it will work because I don't have the file to test yet. Is this the right way? Or is there a better way to do it?
FileInputStream fis = new FileInputStream("sourcefile");
DataInputStream dis = new DataInputStream(fis);
dis.skipBytes(0x270 );
File tmpFile = new File("destfile.zip");
tmpFile.createNewFile();
FileOutputStream fos = new FileOutputStream(tmpFile, false);
int read;
byte[] bytes = new byte[0x10];
while ((read = dis.read(bytes)) != -1) {
fos.write(bytes, 0, read);
}
fis.close();
fos.close();
The code looks correct. There are other ways to do this, but nothing that is unequivocally better. (Especially since you did not give us a clear quantifiable "goodness" measure.)
There are however a couple of things to note:
You are copying the file using a buffer that is way too small. I'd use a 64K byte buffer, not a 16 byte buffer. If you read / write using a tiny buffer you spend more time on system call overheads. With a buffer this small the overheads are likely to be significant, especially as the input file gets larger.
Since the FileInputStream
class has skip(long)
method, the DataInputStream
class is not strictly necessary here.
Also:
"I am considering trying this, but I am unsure if it will work because I don't have the file to test yet."
Surely you can make a file ... for test purposes. For example, on Linux you can create a stream containing 0x270
zero bytes and append a normal ZIP file to it. It can probably done in one line using dd
and cat
...