爪哇 - 荏苒现有文件 [英] Java - Zipping existing files
问题描述
可能重复:结果
追加文件与Java
您好Java开发,
下面的情况:搜索结果
说我有一个文本文件名为 sample.txt的
。我真正想要做的是把 sample.txt的
文件转换成一个名为 *。拉链
文件 TextFiles.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
}
我的code到目前为止创建 *。拉链
文件并插入 sample.txt的
文件。结果
我的问题是如何将能够插入现有文件创建 *。ZIP文件?结果
如果你的答案有什么关系 TrueZIP ,请张贴SSCCE。结果< BR>
我也做了以下内容:结果
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:
- Google搜索
- 搜索存在的问题。 (找到几个。没有回答。一些没有回答我的问题,尤其
- 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) {
}
}
}
}
这篇关于爪哇 - 荏苒现有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!