题
我当前正在提取一个 war 文件的内容,然后将一些新文件添加到目录结构中,然后创建一个新的 war 文件。
这一切都是通过Java以编程方式完成的 - 但我想知道复制战争文件然后附加文件是否会更有效 - 然后我就不必等待战争扩大然后必须再次被压缩。
我似乎无法在文档或任何在线示例中找到执行此操作的方法。
任何人都可以提供一些提示或指示吗?
更新:
正如其中一个答案中提到的,TrueZip 似乎是一个非常好的 java 库,可以附加到 zip 文件(尽管其他答案说不可能做到这一点)。
有人对 TrueZip 有经验或反馈吗?或者可以推荐其他类似的库吗?
解决方案
在Java 7中,我们得到 Zip文件系统那允许无需人工重新包装增加和改变在zip文件(JAR,WAR)。
我们可以直接写至zip文件中的文件,如以下示例所示。
Map<String, String> env = new HashMap<>();
env.put("create", "true");
Path path = Paths.get("test.zip");
URI uri = URI.create("jar:" + path.toUri());
try (FileSystem fs = FileSystems.newFileSystem(uri, env))
{
Path nf = fs.getPath("new.txt");
try (Writer writer = Files.newBufferedWriter(nf, StandardCharsets.UTF_8, StandardOpenOption.CREATE)) {
writer.write("hello");
}
}
其他提示
正如其他所提到的,这是不可能的追加内容到现有拉链(或战争)。但是,它可能暂时不写提取的内容到磁盘到动态创建一个新的拉链。很难猜测如何更快,这将是,但它是你可以(至少据我所知)与标准的Java最快的。正如卡洛斯Tasada提到,SevenZipJBindings可能排挤你一些额外秒,但移植这种方法SevenZipJBindings仍比用相同库的临时文件速度更快。
这里的一些写入的现有拉链(war.zip)的内容和追加一个额外的文件(answer.txt)到一个新的拉链(append.zip)码。所需要的是Java 5或更高版本,没有额外的库需要的。
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
public class Main {
// 4MB buffer
private static final byte[] BUFFER = new byte[4096 * 1024];
/**
* copy input to output stream - available in several StreamUtils or Streams classes
*/
public static void copy(InputStream input, OutputStream output) throws IOException {
int bytesRead;
while ((bytesRead = input.read(BUFFER))!= -1) {
output.write(BUFFER, 0, bytesRead);
}
}
public static void main(String[] args) throws Exception {
// read war.zip and write to append.zip
ZipFile war = new ZipFile("war.zip");
ZipOutputStream append = new ZipOutputStream(new FileOutputStream("append.zip"));
// first, copy contents from existing war
Enumeration<? extends ZipEntry> entries = war.entries();
while (entries.hasMoreElements()) {
ZipEntry e = entries.nextElement();
System.out.println("copy: " + e.getName());
append.putNextEntry(e);
if (!e.isDirectory()) {
copy(war.getInputStream(e), append);
}
append.closeEntry();
}
// now append some extra content
ZipEntry e = new ZipEntry("answer.txt");
System.out.println("append: " + e.getName());
append.putNextEntry(e);
append.write("42\n".getBytes());
append.closeEntry();
// close
war.close();
append.close();
}
}
我也有类似的要求,有时回 - 但它是用于读取和写入的ZIP压缩文件(格式的.war应该是相似的)。我试着用现有的Java邮编流,这样做,但发现写入的部分繁琐的 - 尤其是当目录,其中涉及。
我会建议你尝试一下 TrueZIP (开放源 - 阿帕奇风格行货)库,公开的任何档案作为一个虚拟文件系统,可以在其中读取和写入像一个正常的文件系统。它的工作对我来说就像魅力和大大简化了我的发展。
您可以使用这段代码我写了
public static void addFilesToZip(File source, File[] files)
{
try
{
File tmpZip = File.createTempFile(source.getName(), null);
tmpZip.delete();
if(!source.renameTo(tmpZip))
{
throw new Exception("Could not make temp file (" + source.getName() + ")");
}
byte[] buffer = new byte[1024];
ZipInputStream zin = new ZipInputStream(new FileInputStream(tmpZip));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(source));
for(int i = 0; i < files.length; i++)
{
InputStream in = new FileInputStream(files[i]);
out.putNextEntry(new ZipEntry(files[i].getName()));
for(int read = in.read(buffer); read > -1; read = in.read(buffer))
{
out.write(buffer, 0, read);
}
out.closeEntry();
in.close();
}
for(ZipEntry ze = zin.getNextEntry(); ze != null; ze = zin.getNextEntry())
{
out.putNextEntry(ze);
for(int read = zin.read(buffer); read > -1; read = zin.read(buffer))
{
out.write(buffer, 0, read);
}
out.closeEntry();
}
out.close();
tmpZip.delete();
}
catch(Exception e)
{
e.printStackTrace();
}
}
我不知道一个Java库,做你描述的。但是,你所描述的是实用。你可以做到这一点在.NET中,使用 DotNetZip 。
迈克尔Krauklis是正确的,你不能简单地数据“追加”到war文件或zip文件,但它不是,因为有迹象显示“文件结束”,严格来说,在战争文件。这是因为,战争(ZIP)格式包括目录,其通常存在于文件的末尾,包含元数据对于在战争文件中的各种条目。天真地追加到WAR文件导致没有更新的目录,所以你只要有垃圾附加一个WAR文件。
什么是必要的是一个智能的类,理解的格式,并能读+更新WAR文件或压缩文件,包括目录合适。 DotNetZip做到这一点,没有解压缩/再压缩不变条目,就像你描述或期望。
正如 Cheeso 所说,没有办法做到这一点。AFAIK zip 前端的功能与您内部的功能完全相同。
无论如何,如果您担心提取/压缩所有内容的速度,您可能想尝试 SevenZipJBindings 图书馆。
我在我的文章中介绍了这个图书馆 博客 几个月前(抱歉自动促销)。举个例子,使用 java.util.zip 提取 104MB 的 zip 文件花了我 12 秒,而使用这个库花了 4 秒。
在这两个链接中,您都可以找到有关如何使用它的示例。
希望能帮助到你。
请参阅此错误报告。
使用任何种类附加模式 结构化数据像zip文件或焦油 文件是不是你真的可以 预期工作。这些文件格式 有一个内在的“文件结束” 指示内置到数据格式。
如果你真的想跳过未华林/重新华林的中间步骤,你可以阅读战争文件档案,让所有的ZIP条目,然后写一个新的战争文件“追加”你想要的新条目加上。并不完美,但至少一个更自动化的解决方案。
又一解决方案:可以在其他情况下在下面找到有用的代码为好。我用蚂蚁这种方式来编译Java目录,生成jar文件,更新zip文件,...
public static void antUpdateZip(String zipFilePath, String libsToAddDir) {
Project p = new Project();
p.init();
Target target = new Target();
target.setName("zip");
Zip task = new Zip();
task.init();
task.setDestFile(new File(zipFilePath));
ZipFileSet zipFileSet = new ZipFileSet();
zipFileSet.setPrefix("WEB-INF/lib");
zipFileSet.setDir(new File(libsToAddDir));
task.addFileset(zipFileSet);
task.setUpdate(true);
task.setProject(p);
task.init();
target.addTask(task);
target.setProject(p);
p.addTarget(target);
DefaultLogger consoleLogger = new DefaultLogger();
consoleLogger.setErrorPrintStream(System.err);
consoleLogger.setOutputPrintStream(System.out);
consoleLogger.setMessageOutputLevel(Project.MSG_DEBUG);
p.addBuildListener(consoleLogger);
try {
// p.fireBuildStarted();
// ProjectHelper helper = ProjectHelper.getProjectHelper();
// p.addReference("ant.projectHelper", helper);
// helper.parse(p, buildFile);
p.executeTarget(target.getName());
// p.fireBuildFinished(null);
} catch (BuildException e) {
p.fireBuildFinished(e);
throw new AssertionError(e);
}
}
此简单的代码来获得与使用的servlet的响应,并发送响应
myZipPath = bla bla...
byte[] buf = new byte[8192];
String zipName = "myZip.zip";
String zipPath = myzippath+ File.separator+"pdf" + File.separator+ zipName;
File pdfFile = new File("myPdf.pdf");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath));
ZipEntry zipEntry = new ZipEntry(pdfFile.getName());
out.putNextEntry(zipEntry);
InputStream in = new FileInputStream(pdfFile);
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
out.close();
FileInputStream fis = new FileInputStream(zipPath);
response.setContentType("application/zip");
response.addHeader("content-disposition", "attachment;filename=" + zipName);
OutputStream os = response.getOutputStream();
int length = is.read(buffer);
while (length != -1)
{
os.write(buffer, 0, length);
length = is.read(buffer);
}
下面就是Java 1.7版利亚姆答案的,它使用的资源和Apache下议院IO。
尝试的输出被写入到一个新的压缩文件,但它可以很容易地修改,以写入到原始文件。
/**
* Modifies, adds or deletes file(s) from a existing zip file.
*
* @param zipFile the original zip file
* @param newZipFile the destination zip file
* @param filesToAddOrOverwrite the names of the files to add or modify from the original file
* @param filesToAddOrOverwriteInputStreams the input streams containing the content of the files
* to add or modify from the original file
* @param filesToDelete the names of the files to delete from the original file
* @throws IOException if the new file could not be written
*/
public static void modifyZipFile(File zipFile,
File newZipFile,
String[] filesToAddOrOverwrite,
InputStream[] filesToAddOrOverwriteInputStreams,
String[] filesToDelete) throws IOException {
try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(newZipFile))) {
// add existing ZIP entry to output stream
try (ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile))) {
ZipEntry entry = null;
while ((entry = zin.getNextEntry()) != null) {
String name = entry.getName();
// check if the file should be deleted
if (filesToDelete != null) {
boolean ignoreFile = false;
for (String fileToDelete : filesToDelete) {
if (name.equalsIgnoreCase(fileToDelete)) {
ignoreFile = true;
break;
}
}
if (ignoreFile) {
continue;
}
}
// check if the file should be kept as it is
boolean keepFileUnchanged = true;
if (filesToAddOrOverwrite != null) {
for (String fileToAddOrOverwrite : filesToAddOrOverwrite) {
if (name.equalsIgnoreCase(fileToAddOrOverwrite)) {
keepFileUnchanged = false;
}
}
}
if (keepFileUnchanged) {
// copy the file as it is
out.putNextEntry(new ZipEntry(name));
IOUtils.copy(zin, out);
}
}
}
// add the modified or added files to the zip file
if (filesToAddOrOverwrite != null) {
for (int i = 0; i < filesToAddOrOverwrite.length; i++) {
String fileToAddOrOverwrite = filesToAddOrOverwrite[i];
try (InputStream in = filesToAddOrOverwriteInputStreams[i]) {
out.putNextEntry(new ZipEntry(fileToAddOrOverwrite));
IOUtils.copy(in, out);
out.closeEntry();
}
}
}
}
}
本工程100%,如果你不想使用额外的库.. 1)首先,追加文件到拉链类..
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class AddZip {
public void AddZip() {
}
public void addToZipFile(ZipOutputStream zos, String nombreFileAnadir, String nombreDentroZip) {
FileInputStream fis = null;
try {
if (!new File(nombreFileAnadir).exists()) {//NO EXISTE
System.out.println(" No existe el archivo : " + nombreFileAnadir);return;
}
File file = new File(nombreFileAnadir);
System.out.println(" Generando el archivo '" + nombreFileAnadir + "' al ZIP ");
fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(nombreDentroZip);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {zos.write(bytes, 0, length);}
zos.closeEntry();
fis.close();
} catch (FileNotFoundException ex ) {
Logger.getLogger(AddZip.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(AddZip.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
2),则可以调用它在控制器..
//in the top
try {
fos = new FileOutputStream(rutaZip);
zos = new ZipOutputStream(fos);
} catch (FileNotFoundException ex) {
Logger.getLogger(UtilZip.class.getName()).log(Level.SEVERE, null, ex);
}
...
//inside your method
addZip.addToZipFile(zos, pathFolderFileSystemHD() + itemFoto.getNombre(), "foto/" + itemFoto.getNombre());
以下是如何轻松地将文件附加到现有 zip 的示例 真实VFS:
// append a file to archive under different name
TFile.cp(new File("existingFile.txt"), new TFile("archive.zip", "entry.txt"));
// recusively append a dir to the root of archive
TFile src = new TFile("dirPath", "dirName");
src.cp_r(new TFile("archive.zip", src.getName()));
TrueVFS 是 TrueZIP 的后继者,在适当的情况下使用 Java 7 NIO 2 功能,但提供 更多功能 就像线程安全的异步并行压缩。
还要注意,Java 7 ZipFileSystem 默认情况下是 容易受到 OutOfMemoryError 的影响 依靠巨大的投入。