Java - 压缩现有文件 [英] Java - Zipping existing files
问题描述
可能的重复:
使用 Java 将文件附加到 zip 文件
Java 开发人员,您好
Hello Java Developers,
场景如下:
假设我有一个名为 sample.txt
的文本文件.我真正想做的是将 sample.txt
文件放入名为 TextFiles.zip
的 *.zip
文件中.
这是我目前学到的东西.
Here's the scenario:
Say I have a textfile named sample.txt
. What I actually want to do is to put the sample.txt
file into a *.zip
file named TextFiles.zip
.
Here's what I have learned so far.
try{
File f = new File(compProperty.getZIP_OUTPUT_PATH());
zipOut = new ZipOutputStream(new FileOutputStream(f));
ZipEntry zipEntry = new ZipEntry("sample.txt");
zipOut.putNextEntry(zipEntry);
zipOut.closeEntry();
zipOut.close();
System.out.println("Done");
} catch ( Exception e ){
// My catch block
}
到目前为止,我的代码创建了一个 *.zip
文件并插入了 sample.txt
文件.
我的问题是如何将现有文件插入到创建的 *.zip
文件中?
如果您的回答与 TrueZIP 有关,请发布 SSCCE.
我做了以下事情:
My code so far creates a *.zip
file and insert the sample.txt
file.
My question is how would I be able to insert an existing file to the created *.zip
file?
If your answer has anything to do with TrueZIP, please post an SSCCE.
I have done the following:
- 谷歌搜索
- 搜索现有问题.(发现很少.没有答案.有些没有回答我的特定问题.
- 阅读TrueZip.然而,我什么也听不懂.(请理解)
- Googled
- Search for existing question. ( Found few. No answer. Some didn't answer my particular question.
- Read TrueZip. Yet, I couldn't understand a thing. ( Please do understand )
推荐答案
使用内置的 Java API.这会将文件添加到 Zip 文件,这将替换可能存在的任何现有 Zip 文件,创建一个新的 Zip 文件.
Using the inbuilt Java API. This will add a file to a Zip File, this will replace any existing Zip files that may exist, creating a new Zip file.
public class TestZip02 {
public static void main(String[] args) {
try {
zip(new File("TextFiles.zip"), new File("sample.txt"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void zip(File zip, File file) throws IOException {
ZipOutputStream zos = null;
try {
String name = file.getName();
zos = new ZipOutputStream(new FileOutputStream(zip));
ZipEntry entry = new ZipEntry(name);
zos.putNextEntry(entry);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
byte[] byteBuffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = fis.read(byteBuffer)) != -1) {
zos.write(byteBuffer, 0, bytesRead);
}
zos.flush();
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
zos.closeEntry();
zos.flush();
} finally {
try {
zos.close();
} catch (Exception e) {
}
}
}
}
这篇关于Java - 压缩现有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!