java - 写入 ZIP 文件的文件仅在运行时可用 [Java]

标签 java path filesystems java-7 nio

我在使用 Java 7 的 FileSystemFiles 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/

相关文章:

linux - 在 Bash 中获取 '~' 缩写路径

python - excel文件的相对路径,python

c++ - 在 C++ 中创建文件夹

c - 使用C直接读/写磁盘

java - Spring EL 不起作用

java - 测试两个迭代器的相等性?

linux - 启动 .desktop 文件时如何包含我的 bash 路径

java - 终端与 Eclipse PosixFilePermissions

java - 我怎样才能正确地将数据分配给两个消费者?

java - 找不到变量 e.getkeycode