开发者

How to read and write a zip file in java?

I am doing a practice to understand read and write zip files in java. I'd read about reading a file and making it to zip file, and i have also tried. I'd read about reading a zip file using java. How can i combine this read and write operations together. Like, i want to read a zipped file in HDD and i want to save it in a another location.

I am able read zip file with this code:

FileInputStream fs = new FileInputStream("C:/Documents and Settings/tamilvendhank/Desktop/abc.zip");
ZipInputStream zis = new ZipInputStream(fs);
ZipEntry zE;
while((zE=zis.getNextEntry())!=null){
    System.out.println(ze.getName());
    zis.closeEntry();
  }

zis.close();

And, i am also able make a text file to zip with this code:

String fn = "C:/Documents and Settings/tamilvendhank/Desktop/New Text Document.txt";
byte[] b = new byte[1024];
FileInputStream fis = new FileInputStream(fn);
fis.read(b, 0, b.length);
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("C:/Documents and Settings/tamilvendhank/Desktop/123.zip"));
ZipEntry ze = new ZipEntry(fn);
ze.setSize((long)b.length);
zos.setLevel(6);
zos.putNextEntry(ze);
zos.write(开发者_高级运维b, 0, b.length);
zos.finish();
zos.close();

Now how i shall connect the above two codes and make the code to read a zip file and write it in a different location.

Any Suggestions!!


Why don't you open it up as a FileInputStream and dump the contents over into a FileOutputStream. This is how a simple copy operation is performed, you don't have to unzip the file and then zip it back on another location on HDD.


Your question seems to be more of how to connect an input stream and an output stream, reading from one and writing from the other.

The answer is to use a while loop that reads chunks from the input and writes them to the output. Something like this;

byte[] data = new byte[2048];
int b = -1;
while ((b = is.read(data)) != -1)
{
   fos.write(data, 0, b);
}

is.close();
fos.close();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜