創建一個名爲zip文件output.zip包含文件1.txt的,2.txt和3.txt他們的內容字符串,請嘗試以下操作:
Map<String, String> entries = new HashMap<String, String>();
entries.put("firstContent", "1.txt");
entries.put("secondContent", "2.txt");
entries.put("thirdContent", "3.txt");
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream("output.zip");
zos = new ZipOutputStream(fos);
for (Map.Entry<String, String> mapEntry : entries.entrySet()) {
ZipEntry entry = new ZipEntry(mapEntry.getValue()); // create a new zip file entry with name, e.g. "1.txt"
entry.setMethod(ZipEntry.DEFLATED); // set the compression method
zos.putNextEntry(entry); // add the ZipEntry to the ZipOutputStream
zos.write(mapEntry.getKey().getBytes()); // write the ZipEntry content
}
} catch (FileNotFoundException e) {
// do something
} catch (IOException e) {
// do something
} finally {
if (zos != null) {
zos.close();
}
}
有關更多信息,請參閱Creating ZIP and JAR files,特別是章節壓縮文件。
字符串是否保存要壓縮的文件的文件名,或者你想壓縮字符串本身嗎? – Jias 2013-04-26 19:29:32