You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何动态截取目录路径 删除末尾两层目录及结尾斜杠

Java移除路径末尾两层目录的简洁实现方式

推荐优先使用JDK 7及以上内置的java.nio.file.Path工具类实现,无需手动处理字符串分割拼接逻辑,同时兼容不同操作系统的路径格式,实现代码如下:

import java.nio.file.Path;
import java.nio.file.Paths;

public class PathProcessDemo {
    public static void main(String[] args) {
        String filePath = "/tmp/test/save/data/java/";
        // Path会自动忽略末尾的斜杠,连续调用两次getParent()即可移除最后两层目录
        String result = Paths.get(filePath)
                            .getParent()
                            .getParent()
                            .toString();
        System.out.println(result); // 输出结果:/tmp/test/save
    }
}

如果希望用纯字符串逻辑实现,不需要引入额外的IO类,可以通过两次lastIndexOf定位截断位置,代码如下:

public class PathProcessDemo {
    public static void main(String[] args) {
        String filePath = "/tmp/test/save/data/java/";
        // 先移除末尾所有多余的斜杠
        String temp = filePath.replaceAll("/+$", "");
        // 连续两次从末尾定位斜杠位置并截断
        temp = temp.substring(0, temp.lastIndexOf('/'));
        String result = temp.substring(0, temp.lastIndexOf('/'));
        System.out.println(result); // 输出结果:/tmp/test/save
    }
}

注意:如果实际场景中路径的层级可能少于3层,建议增加空判断或者边界校验,避免出现索引越界或者空指针异常。

内容的提问来源于stack exchange,提问作者guy_sensei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 23:30:05