编辑:我认识到FileSystem.getDefault()会在我原来的问题陈述中给出我想要的内容。我正在尝试使用FileSystem.getFileSystem(URI)来获取任何给定路径的FileSystem。
我正在尝试开发一些代码,它将为我提供给定路径的java.nio.file.FileSystem对象。
这是一些非常简化的示例代码,可以更好地了解正在尝试的内容:
public FileSystem getCwdFilesystem()
{
URI cwdUri = null;
String delimiter = "";
try
{
_cwd = System.getProperty("user.dir");
cwdUri = new URI("file", delimiter + _cwd, null);
}
catch (URISyntaxException ue)
{
System.out.println("URI Creation failure on URI: " + _cwd);
ue.printStackTrace();
System.exit(1);
}
System.out.println("Filestore data for CWD: " + cwdUri.toString());
return (FileSystems.getFileSystem(cwdUri));
}
执行时,会在最后一行代码中抛出异常:
Filestore data for CWD: file:/Users/redacted/Documents/Java%20Projects/ExampleCode
Exception in thread "main" java.lang.IllegalArgumentException: Path component should be '/'
at sun.nio.fs.UnixFileSystemProvider.checkUri(UnixFileSystemProvider.java:77)
at sun.nio.fs.UnixFileSystemProvider.getFileSystem(UnixFileSystemProvider.java:92)
at java.nio.file.FileSystems.getFileSystem(FileSystems.java:217)
at examplecode.FilesystemCapacity.getCwdFilesystem(FilesystemCapacity.java:54)
at examplecode.FilesystemCapacity.main(FilesystemCapacity.java:33)
Java Result: 1
当我对分隔符变量进行小的更新时:
String delimiter = "/";
我从同一个地方抛出了不同的错误消息:
Filestore data for CWD: file://Users/redacted/Documents/Java%20Projects/ExampleCode
Exception in thread "main" java.lang.IllegalArgumentException: Authority component present
at sun.nio.fs.UnixFileSystemProvider.checkUri(UnixFileSystemProvider.java:73)
at sun.nio.fs.UnixFileSystemProvider.getFileSystem(UnixFileSystemProvider.java:92)
at java.nio.file.FileSystems.getFileSystem(FileSystems.java:217)
at examplecode.FilesystemCapacity.getCwdFilesystem(FilesystemCapacity.java:54)
at examplecode.FilesystemCapacity.main(FilesystemCapacity.java:33)
Java Result: 1
在分隔符中添加其他“/”字符只会让我再次收到第一条错误消息。
我做错了什么?
答案 0 :(得分:2)
我找到了一个我之前错过了NIO.2文档记录on the last page的引用。
我写了一些测试代码,这些代码完全符合我的要求:
public void getPathFilesystem(String path)
{
try
{
URI rootURI = new URI("file:///");
Path rootPath = Paths.get(rootURI);
Path dirPath = rootPath.resolve(path);
FileStore dirFileStore = Files.getFileStore(dirPath);
printFileStore(dirFileStore, path);
}
catch (IOException | URISyntaxException e)
{
e.printStackTrace();
}
}
public void printFileStore(FileStore filestore, String path)
{
try
{
System.out.println("Name: " + filestore.name());
System.out.println("\tPath: " + path);
System.out.println("\tSize: " + filestore.getTotalSpace());
System.out.println("\tUnallocated: " + filestore.getUnallocatedSpace());
System.out.println("\tUsable: " + filestore.getUsableSpace());
System.out.println("\tType: " + filestore.type());
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}