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

如何利用File类的getParent()和getName()获取Desktop/1.txt格式的字符串文件名?

Java File类路径操作问题解答

嗨,我来帮你理清这两个问题哈~

1. 文件名字符串能直接调用getParent()和getName()吗?

当然不行啦!getParent()和getName()是File类的实例方法,不是String类自带的方法。你必须先把文件名字符串转换成File对象,才能调用这两个方法,就像你示例里写的那样:

File f = new File("/home/jigar/Desktop/1.txt");
System.out.println(f.getParent());// 输出/home/jigar/Desktop
System.out.println(f.getName()); //输出1.txt

(对啦,你示例里说“输出1.txt的内容”是笔误哦,getName()只会返回文件名,不会读取文件内容哒)

2. 如何获取「Desktop/1.txt」格式的字符串?

有两种常用的方式,看你偏好哪种:

方式一:用File类拼接

如果已经有了File对象,可以通过获取父目录的名称,再拼接文件名来实现:

File f = new File("/home/jigar/Desktop/1.txt");
// 用系统默认路径分隔符拼接,适配Windows/Linux
String targetPath = f.getParentFile().getName() + File.separator + f.getName();
System.out.println(targetPath); // 输出Desktop/1.txt(Linux下)或Desktop\1.txt(Windows下)

方式二:用NIO的Path类(Java 7+推荐)

Java 7之后推出的NIO Path API更灵活,能直接截取路径的最后两段:

Path path = Paths.get("/home/jigar/Desktop/1.txt");
// subpath(startIndex, endIndex):从第startIndex个节点取到endIndex-1个节点
String targetPath = path.subpath(path.getNameCount() - 2, path.getNameCount()).toString();
System.out.println(targetPath); // 输出Desktop/1.txt

这种方式会自动处理不同系统的路径分隔符,代码更简洁可靠。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 10:12:49