【发布时间】:2019-02-08 06:55:36
【问题描述】:
我正在创建一个命令行应用程序,它需要根据给定的参数将一些文件(多个)输出到 ZIP 文件 或 普通文件夹 .
我的方法是用FileSystem 封装目标(普通文件夹/ZIP 文件)。
我的问题是我无法成功地为 当前工作目录 以外的 目录 创建一个 FileSystem 对象,该目录表示绝对路径在我的硬盘上:
public class FileSystemWriteTest {
public static void main(String[] args) throws IOException {
Path absolutePath = Paths.get("target", "testpath").toAbsolutePath();
System.out.println(String.format("user.dir before change:\n %s", System.getProperty("user.dir")));
System.setProperty("user.dir", absolutePath.toString());
System.out.println(String.format("changed user.dir:\n %s", System.getProperty("user.dir")));
FileSystem defaultSystem = FileSystems.getDefault();
Path testFilePath = defaultSystem.getPath("test.file");
System.out.println(String.format("expected to be in changed user.dir:\n %s", testFilePath.toAbsolutePath()));
URI uri = absolutePath.toUri();
System.out.println(String.format("URI: %s", uri));
FileSystem localFileSystem =
FileSystems.newFileSystem(uri, Collections.emptyMap());
Path file = localFileSystem.getPath("test.txt");
System.out.println(file.toAbsolutePath());
}
}
输出是:
user.dir before change:
D:\data\scm-workspace\anderes\Test
changed user.dir:
D:\data\scm-workspace\anderes\Test\target\testpath
expected to be in changed user.dir:
D:\data\scm-workspace\anderes\Test\test.file
URI: file:///D:/data/scm-workspace/anderes/Test/target/testpath/
Exception in thread "main" java.lang.IllegalArgumentException: Path component should be '/'
at sun.nio.fs.WindowsFileSystemProvider.checkUri(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.newFileSystem(Unknown Source)
at java.nio.file.FileSystems.newFileSystem(Unknown Source)
at java.nio.file.FileSystems.newFileSystem(Unknown Source)
at com.oc.test.filesystem.FileSystemWriteTest.main(FileSystemWriteTest.java:27)
如果我更改为FileSystems.newFileSystem(Path, Classloader),则异常更改为:
Exception in thread "main" java.nio.file.ProviderNotFoundException: Provider not found
at java.nio.file.FileSystems.newFileSystem(Unknown Source)
at com.oc.test.filesystem.FileSystemWriteTest.main(FileSystemWriteTest.java:27)
看起来这只适用于常规文件,不适用于目录。
那么如何为 pwd 以外的目录 创建FileSystem 对象?
【问题讨论】:
-
鉴于您的要求(第一句话),我认为
java.nio.file.FileSystem不是一个有用的方法。为什么不使用java.io.File和java.util.zip.ZipFile? -
@Würgspaß 因为有不同的方法来创建一个新的“文件”。我不希望代码实际创建需要知道使用什么目标的文件。 (所有文件都应该放在同一个 ZIP 或目录中)
-
创建新文件系统需要适当的文件系统提供程序实现。 JDK没有自带这样的目录封装文件系统。
-
@Holger 那么
FileSystems.getDefault()如何以root 身份返回pwd? -
FileSystems.getDefault()确实不使用密码作为根。调用FileSystems.getDefault().getRootDirectories()时会得到根目录。您所做的只是解析相对路径,这总是针对当前目录发生的。这不会使它成为一个根。您仍然可以解析相关路径,例如..,或者在 Windows 的情况下,\。在这方面,FileSystems.getDefault().getPath("test.file")和Paths.get("test.file")没有区别。
标签: java java-io java.nio.file