Ord*_*iel 10 java filesystems zip file
我已经使用FileSystemjava 7提供的成功修改了(现有)zip文件的内容,但是当我尝试通过此方法创建一个新的zip文件时,它失败了,并显示错误消息:"zip END header not found",这是合乎逻辑的,因为我这样做的方式,首先我创建一个文件(Files.createFile),这是一个完全空的文件,然后我尝试访问它的文件系统,因为文件是空的,它不可能在zip中找到任何标题,我的问题是有没有办法用这个方法创建一个完全空的新zip文件?我考虑过的黑客是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);
.
.
.
Run Code Online (Sandbox Code Playgroud)
zipLocation是一个路径
creatingFile是一个布尔值
答案: 在我的特定情况下,由于路径中的空格,给出的答案不能正常工作,因此我必须按照我不想要的方式进行:
Files.createFile(zipLocation);
ZipOutputStream out = new ZipOutputStream(
new FileOutputStream(zipLocation.toFile()));
out.putNextEntry(new ZipEntry(""));
out.closeEntry();
out.close();
Run Code Online (Sandbox Code Playgroud)
这并不意味着给定的答案是错误的,它只是对我的具体情况不起作用
Car*_*ini 19
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");
}
Run Code Online (Sandbox Code Playgroud)