java.nio.file.Path的subpath(int beginIndex,int endIndex)方法用于返回相对路径,该相对路径是此路径的名称元素的子序列。我们将通过开始索引和结束索引来构建子路径。 beginIndex和endIndex参数指定名称元素的子序列。在目录层次结构中最接近根的name元素是索引0,而离根最远的name元素的索引是count-1。返回的子路径对象具有以beginIndex开头并扩展到索引endIndex-1的元素。
用法:
Path subpath(int beginIndex,
int endIndex)
参数:此方法接受两个参数:
beginIndex这是第一个元素的索引,包括和
endIndex这是最后一个元素的索引,不包括索引。
返回值:此方法返回一个新的Path对象,该对象是该Path中名称元素的子序列。
异常:如果beginIndex为负或大于或等于元素数,则此方法引发IllegalArgumentException。如果endIndex小于或等于beginIndex,或者大于元素数。
以下示例程序旨在说明subpath()方法:
示例1:
// Java program to demonstrate
// java.nio.file.Path.subpath() method
import java.nio.file.Path;
import java.nio.file.Paths;
public class GFG {
public static void main(String[] args)
{
// create an object of Path
Path path
= Paths.get("D:\\eclipse\\p2"
+ "\\org\\eclipse\\equinox\\p2\\core"
+ "\\cache\\binary");
// call subPath() to create a subPath which
// begin at index 1 and ends at index 5
Path subPath = path.subpath(1, 5);
// print result
System.out.println("Subpath: "
+ subPath);
}
}
输出:
示例2:
// Java program to demonstrate
// java.nio.file.Path.subpath() method
import java.nio.file.Path;
import java.nio.file.Paths;
public class GFG {
public static void main(String[] args)
{
// create an object of Path
Path path
= Paths.get("D:\\Workspace"
+ "\\nEclipseWork"
+ "\\GFG\\bin\\defaultpackage");
System.out.println("Original Path:"
+ path);
// call subPath() to create a subPath which
// begin at index 0 and ends at index 2
Path subPath = path.subpath(0, 2);
// print result
System.out.println("Subpath: "
+ subPath);
}
}
输出: