你的位置:首页 > Java教程

[Java教程]2.2.2 从 Path 中获取信息


Demo:

import java.nio.file.Path;import java.nio.file.Paths;public class PathInfoTest {    public static void main(String[] args) {        // 创建绝对路径(位置)    Path listing = Paths.get("/Users/jinxing/Documents/pathtest");        System.out.println("File Name: " +        // 位置(文件)名称        listing.getFileName());        System.out.println("Number of Name Elements in the Path: " +        // (位置)路径层级 / 元素数量        listing.getNameCount());        System.out.println("Parent Path: " +        // 上级位置 / 上级文件路径        listing.getParent());        System.out.println("Root of Path: " +        // 跟位置(路径)        listing.getRoot());        System.out.println("Subpath from Root,2 elements deep: " +        // 截断路径——从第1个反斜杠开始截取到第3个反斜杠——反斜杠计数从0开始——结果不包含头尾反斜杠        // /Users/jinxing/Documents/pathtest --> jinxing/Documents        listing.subpath(1, 3));      }}

Ran As Java Application:

File Name: pathtestNumber of Name Elements in the Path: 4Parent Path: /Users/jinxing/DocumentsRoot of Path: /Subpath from Root,2 elements deep: jinxing/Documents