java 如何在java中读取和写入zip文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4146402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:01:14  来源:igfitidea点击:

How to read and write a zip file in java?

java

提问by

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.

我正在做一个练习来理解在 Java 中读写 zip 文件。我读过有关读取文件并将其压缩为 zip 文件的内容,我也尝试过。我读过有关使用 java 读取 zip 文件的信息。我如何将这种读写操作结合在一起。就像,我想读取 HDD 中的压缩文件,并且想将其保存在另一个位置。

I am able read zip file with this code:

我可以使用以下代码读取 zip 文件:

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.

现在我将如何连接上述两个代码并使代码读取 zip 文件并将其写入不同的位置。

Any Suggestions!!

有什么建议!!

采纳答案by Faisal Feroz

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.

为什么不将它作为 FileInputStream 打开并将内容转储到 FileOutputStream 中。这是执行简单复制操作的方式,您不必解压缩文件,然后将其压缩回 HDD 上的另一个位置。

回答by Qwerky

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;

答案是使用 while 循环从输入读取块并将它们写入输出。像这样的东西;

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

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