使用java.nio分割路径的简明方法?

时间:2015-01-21 01:48:35

标签: java nio

我正在尝试使用Path.subpath拆分路径,但结果代码似乎非常冗长。 是否有更简洁/惯用的方式来实现这一目标?

//input from elsewhere
String userInput = "foo/bar//baz/";
int splitPoint = 1; 

Path startPath = Paths.get(userInput).normalize();
int nameCount = startPath.getNameCount();
String leftSide = splitPoint > 0 
    ? Paths.get("/", startPath.subpath(0, splitPoint).toString()).toString()
    : "/";
String rightSide = splitPoint < nameCount 
    ? Paths.get("/", startPath.subpath(splitPoint, nameCount).toString()).toString()
    : "/";

请注意,我需要两个生成的String路径以“/”开头。我知道有关路径分隔符和其他文件系统细节的特定于平台的问题。

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

final int nameCount = startPath.getNameCount();

final List<Path> elements = new ArrayList<>(nameCount);

for (int i = 0; i < nameCount; i++)
    list.add(startPath.getName(i));

final Path head = Paths.get("/");
final Path tail = Paths.get("/");

for (final Path entry: elements.sublist(0, splitPoint))
    head = head.resolve(entry);

for (final Path entry: elements.sublist(splitPoint, nameCount))
    tail = tail.resolve(entry);