如何在java中的字符串中拆分目录路径组件

时间:2012-10-24 11:31:51

标签: java string file directory split

  

可能重复:
  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());

Root:C:\ Users \ RS \ Desktop 主目录:C:\ Users \ RS \ Desktop

我想剪切根目录或主目录组件 字符串C,用户,RS,桌面

7 个答案:

答案 0 :(得分:9)

当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());

将输出:

    Path=Other
    Path=Or
    Path=Folder with spaces
    Path=Some
    Root=c:\

您可能希望首先使用f.getCanonicalPath或f.getAbsolutePath,因此它也适用于相对路径。

不幸的是,这需要root的f.getPath和其他部分的f.getName,我需要按向后顺序创建部件。

更新:您可以在向上扫描时将f与fsv.getHomeDirectory()进行比较,并在结果显示您在主文件夹的子目录中时将其中断。

答案 1 :(得分:4)

根据user844382的回答,这是分割路径的平台安全方式:

 String homePath = FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath();
 System.out.println(homePath);
 System.out.println(Arrays.deepToString(homePath.split(Matcher.quoteReplacement(System.getProperty("file.separator")))));        
}       

在linux上输出:

/home/isipka
[, home, isipka]

在Windows上输出:

C:\Documents and Settings\linski\Desktop
[C:, Documents and Settings, linski, Desktop]

如果省略Matcher.quoteReplacement()方法调用,代码将在Windows上失败。此方法处理特殊字符的转义,例如“\”(Windows上为file separator)和“$”。

答案 2 :(得分:3)

您可以使用java.nio.file.Path:

FileSystemView fsv = FileSystemView.getFileSystemView();
File[] roots = fsv.getRoots();
for (int i = 0; i < roots.length; i++)
{
  System.out.println("Root: " + roots[i]);
  Path p = roots[i].toPath();
  for (int j=0; j < p.getNameCount(); j++)
     System.out.println(p.getName(j));
}
System.out.println("Home directory: " + fsv.getHomeDirectory());

答案 3 :(得分:2)

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());

答案 4 :(得分:1)

尝试使用正则表达式拆分root.split(":?\\\\")

答案 5 :(得分:1)

与其他解决方案不同的解决方案是从File API获取名称:

File file = roots[i];
while (file != null) {
  if (file.getName().length() > 0) {
    System.out.println(file.getName());
  } else {
    System.out.println(file.getPath().substring(0, 1));
  }
  file = file.getParentFile();
}

此解决方案以相反的顺序返回路径,因此您必须进行一些小的更改。

答案 6 :(得分:0)

尝试使用String.split()方法。 http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split(java.lang.String

分割时需要正则表达式,因此可以做一些非常高级的东西。对于您按\\分割,可能会这样做。

由于\为正则表达式添加了功能,我们需要将其标记为字符而不是“正则表达式运算符”。这解释了双重。