roh*_*ora 3 java string directory split file
可能重复:
如何在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());
Run Code Online (Sandbox Code Playgroud)
Root:C:\ Users\RS\Desktop主目录:C:\ Users\RS\Desktop
我想剪切根或主目录组件,如字符串C,用户,RS,桌面
hyp*_*man 10
当java有自己更清晰的跨平台函数进行路径操作时,我宁愿不屈服于使用split ona文件名的诱惑.
我认为这个基本模式适用于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());
Run Code Online (Sandbox Code Playgroud)
将输出:
Path=Other
Path=Or
Path=Folder with spaces
Path=Some
Root=c:\
Run Code Online (Sandbox Code Playgroud)
您可能希望首先使用f.getCanonicalPath或f.getAbsolutePath,因此它也适用于相对路径.
不幸的是,这需要root的f.getPath和其他部分的f.getName,并且我按向后顺序创建部件.
更新:您可以在向上扫描时将f与fsv.getHomeDirectory()进行比较,并在结果显示您位于主文件夹的子目录中时进行中断.
根据 user844382 的回答,这是分割路径的平台安全方式:
String homePath = FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath();
System.out.println(homePath);
System.out.println(Arrays.deepToString(homePath.split(Matcher.quoteReplacement(System.getProperty("file.separator")))));
}
Run Code Online (Sandbox Code Playgroud)
在linux上它输出:
/home/isipka
[, home, isipka]
Run Code Online (Sandbox Code Playgroud)
在 Windows 上它输出:
C:\Documents and Settings\linski\Desktop
[C:, Documents and Settings, linski, Desktop]
Run Code Online (Sandbox Code Playgroud)
如果省略Matcher.quoteReplacement()方法调用,代码将在 Windows 上失败。此方法处理特殊字符的转义,如“\”(Windows 上的文件分隔符)和“$”。
FileSystemView fsv = FileSystemView.getFileSystemView();
File[] roots = fsv.getRoots();
for (int i = 0; i < roots.length; i++) {
System.out.println("Root: " + roots[i]);
for (String s : roots[i].toString().split(":?\\\\")) {
System.out.println(s);
}
}
System.out.println("Home directory: " + fsv.getHomeDirectory());
Run Code Online (Sandbox Code Playgroud)