我在使用 Java 7 的 FileSystem
和 Files
API 将二进制文件写入简单的 ZIP 存档时遇到问题。
问题发生在执行写操作时,根本不会抛出任何异常,文件没有写入ZIP存档,但在运行时可用(Files.exists(backup)
返回true并且可以使用 Files.readAllBytes(backup)
读取文件。
当程序关闭并重新启动时,该文件不再可用。
片段
此方法应该创建任何路径的备份,无论文件系统提供者是谁,仅在 ZIP 存档内的路径上“失败”。
/**
* Creates backup of path provided by 'file' parameter.
*
* @param file input file requiring backup creation
* @return backup file
* @throws java.io.IOException thrown in case of unsuccessful backup attempt
*/
public static Path createBackup(Path file) throws IOException {
FileSystem fileSystem = file.getFileSystem();
Path backup = fileSystem.getPath(file.toString() + ".BAK");
return Files.write(backup, Files.readAllBytes(file));
}
public static void main(String... args) {
try {
Path f = FileSystems.newFileSystem(Paths.get("a.zip"), null).getPath("file.bin");
Path backup = createBackup(f);
System.out.println(Files.exists(backup)); // prints "true"
System.out.println(new String(Files.readAllBytes(backup))); // prints its bytes
System.out.println(backup.toString()); // prints "file.bin.BAK"
} catch (IOException ex) {
System.err.println(ex);
}
}
但是该文件实际上并不存在于 ZIP 中。
编辑: 我已经设法使它工作,但有一个问题。下面的代码关闭文件系统,但写入正确。需要以某种方式“刷新”/“重新打开”文件系统。
public static Path createBackup(Path file) throws IOException {
try(FileSystem fileSystem = file.getFileSystem()) {
Path backup = fileSystem.getPath(file.toString() + ".BAK");
return Files.write(backup, Files.readAllBytes(file));
}
}
当保留原始方法并在完成所有操作后手动关闭文件系统时,它会删除 zip 文件并保留类似 zipfstmp***.tmp
的内容并抛出:
java.nio.file.FileAlreadyExistsException: zipfstmp2666831581340533856.tmp -> a.zip
当 tmp 文件重命名为“a.zip”时,它是一个有效的修改存档。
最佳答案
您应该在创建文件系统的调用方中使用 try-with-resource 语句来关闭。 createBackup
方法中根本不需要处理文件系统。
public static Path createBackup(Path file) throws IOException {
Path backup = file.resolveSibling(file.getFileName().toString()+".BAK");
return Files.copy(file, backup, StandardCopyOption.REPLACE_EXISTING);
}
public static void main(String... args) {
try(FileSystem fs = FileSystems.newFileSystem(Paths.get("a.zip"), null)) {
Path f = fs.getPath("file.bin");
Path backup = createBackup(f);
System.out.println(Files.exists(backup)); // prints "true"
System.out.println(new String(Files.readAllBytes(backup))); // prints its bytes
System.out.println(backup.toString()); // prints "file.bin.BAK"
} catch (IOException ex) {
System.err.println(ex);
}
}
关于java - 写入 ZIP 文件的文件仅在运行时可用 [Java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45557876/