Possible Duplicate:
how to split the string in java
FileSystemView fsv = FileSystemView.getFileSystemView();
File[] roots = fsv.getRoots();
for (int i = 0; i < roots.length; i++)
{
System.out.println("Root: " + roots[i]);
}
System.out.println("Home directory: " + fsv.getHomeDirectory());
根目录:C:\Users\RS\Desktop
主目录:C:\Users\RS\Desktop
我想削减根目录或主目录组件,例如
字符串 C、用户、RS、桌面
我宁愿不屈服于使用拆分文件名的诱惑,因为 java 有自己更清晰的跨平台路径操作函数。
我认为这个基本模式适用于 java 1.4 及以后的版本:
File f = new File("c:\\Some\\Folder with spaces\\Or\\Other");
do {
System.out.println("Parent=" + f.getName());
f = f.getParentFile();
} while (f.getParentFile() != null);
System.out.println("Root=" + f.getPath());
将输出:
Path=Other
Path=Or
Path=Folder with spaces
Path=Some
Root=c:\
您可能想先使用 f.getCanonicalPath 或 f.getAbsolutePath,因此它也适用于相对路径。
不幸的是,这需要根目录的 f.getPath 和其他部分的 f.getName,我以倒序创建这些部分。
更新:您可以在向上扫描时将 f 与 fsv.getHomeDirectory() 进行比较,并在发现您位于主文件夹的子目录中时中断。