我已经使用 java 7 提供的 FileSystem
成功地修改了一个(现有的)zip 文件的内容,但是当我尝试通过这种方法创建一个新的 zip 文件时它失败了,错误消息显示:"zip END header not found"
,这是合乎逻辑的,因为我正在这样做,首先我创建了文件 (Files.createFile
)这是一个完全空的文件,然后我尝试访问它的文件系统,由于文件是空的,所以不可能在 zip 中找到任何标题,我的问题是有没有办法创建使用此方法的新 zip 文件完全为空?我考虑过的 hack 是将一个空的新 ZipEntry
添加到 zip 文件,然后使用这个新的空文件来创建基于它的文件系统,但我真的想认为这些人oracle 实现了一种更好(更简单)的方法来使用 nio 和文件系统...
这是我的代码(创建文件系统时出现错误):
if (!zipLocation.toFile().exists()) {
if (creatingFile) {
Files.createFile(zipLocation);
}else {
return false;
}
} else if (zipLocation.toFile().exists() && !replacing) {
return false;
}
final FileSystem fs = FileSystems.newFileSystem(zipLocation, null);
.
.
.
zipLocation
是路径
creatingFile
是一个 boolean 值
回答: 在我的特殊情况下,由于路径中的空格,给出的答案无法正常工作,因此我必须按照我不想做的方式去做:
Files.createFile(zipLocation);
ZipOutputStream out = new ZipOutputStream(
new FileOutputStream(zipLocation.toFile()));
out.putNextEntry(new ZipEntry(""));
out.closeEntry();
out.close();
这并不意味着给定的答案是错误的,它只是不适用于我的特定情况
最佳答案
如 The Oracle Site 中所述:
public static void createZip(Path zipLocation, Path toBeAdded, String internalPath) throws Throwable {
Map<String, String> env = new HashMap<String, String>();
// check if file exists
env.put("create", String.valueOf(Files.notExists(zipLocation)));
// use a Zip filesystem URI
URI fileUri = zipLocation.toUri(); // here
URI zipUri = new URI("jar:" + fileUri.getScheme(), fileUri.getPath(), null);
System.out.println(zipUri);
// URI uri = URI.create("jar:file:"+zipLocation); // here creates the
// zip
// try with resource
try (FileSystem zipfs = FileSystems.newFileSystem(zipUri, env)) {
// Create internal path in the zipfs
Path internalTargetPath = zipfs.getPath(internalPath);
// Create parent directory
Files.createDirectories(internalTargetPath.getParent());
// copy a file into the zip file
Files.copy(toBeAdded, internalTargetPath, StandardCopyOption.REPLACE_EXISTING);
}
}
public static void main(String[] args) throws Throwable {
Path zipLocation = FileSystems.getDefault().getPath("a.zip").toAbsolutePath();
Path toBeAdded = FileSystems.getDefault().getPath("a.txt").toAbsolutePath();
createZip(zipLocation, toBeAdded, "aa/aa.txt");
}
关于java - 是否可以使用 java 文件系统创建一个新的 zip 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14733496/