如何使用 FileSystem.getPath() 作为 (File-)Writer 的目标?

How to use FileSystem.getPath() as target for a (File-)Writer?

我有一个可以输出一些文件的应用程序。

根据配置,我需要将它们放在普通文件夹或 zip 文件中。

我正在尝试使用 FileSystem 将实际编写的代码与实际的目标类型分离。

我的问题是,对于由 Zip-FileSystems 创建的 Paths,不支持方法 .tpFile()。因此,我无法创建可以传递给例如 FileWriterFileWriter JaxB.

public class FileSystemWriteTest {
    public static void main(String[] args) throws IOException {
        FileSystem localFileSystem = FileSystems.getDefault();
        File relativeZipPath = Paths.get("target", "testpath").toFile();
        relativeZipPath.mkdirs();
        URI relativeZipFilePath = Paths.get(relativeZipPath.toString(), "test.zip").toUri();

        URI zipUri = URI.create("jar:"
                + relativeZipFilePath);
        System.out.println(zipUri);
        Map<String, String> env = new HashMap<>();
        env.put("create", "true");
        try (FileSystem zipFile = FileSystems.newFileSystem(zipUri, env)) {
            for (FileSystem fs : Arrays.asList(localFileSystem, zipFile)) {
                Path file = fs.getPath("test.txt");
                System.out.println(file.toAbsolutePath());
/* line 31 */   try (FileWriter fileWriter = new FileWriter(file.toFile())) {
                    fileWriter.write("irgend ein Text zum test\nob das so auch geht");
                    fileWriter.flush();
                }
            }
        }

    }
}

投掷

jar:file:///D:/data/scm-workspace/anderes/Test/target/testpath/test.zip
D:\data\scm-workspace\anderes\Test\test.txt
/test.txt
Exception in thread "main" java.lang.UnsupportedOperationException
    at com.sun.nio.zipfs.ZipPath.toFile(ZipPath.java:597)
    at com.oc.test.filesystem.FileSystemWriteTest.main(FileSystemWriteTest.java:31)

我试图实现的是在写入时将 JaxB 输出直接混合到磁盘,而不是在 JaxB 完成之前将其保存在内存中。 (我的 XML 相当大,所以我可能 运行 进入 OOME)

我的问题:
如何从 ZIP 文件支持的 FileSystem 打开合适的 WriterOutputStream

或者:
我还有什么其他的可能性可以从 JaxB 中隐藏真正的写入目标(文件夹与 ZIP 文件)?

像大多数其他文件系统操作一样,可以通过 Files 实用程序 class 打开 OutputStreamWriterChannel

见,例如

但还要注意更高级的方法,例如

但请注意,对于直接流式传输到 zip 文件,在 FileOutputStream 上使用 ZipOutputStream 可能比使用 ZipFileSystem.

更有效