Java 获取文件路径最后三级目录
可以通过以下方式实现:
- 使用File类的getParent()方法获取当前文件或目录的上级目录路径。
- 重复调用getParent()方法,直到获取到需要的层级为止。
- 最后可以通过String类的split()方法,以文件分隔符为分隔符,将路径分割为字符串数组,取最后三个元素即为需要的层级。
示例代码如下:
public static String[] getLastThreeLevels(String filePath) {
File file = new File(filePath);
String[] levels = new String[3];
int count = 0;
while (file != null && count < 3) {
String parentPath = file.getParent();
if (parentPath == null) {
break;
}
levels[count] = file.getName();
file = new File(parentPath);
count++;
}
if (count < 3) {
String[] newLevels = new String[count];
System.arraycopy(levels, 0, newLevels, 0, count);
levels = newLevels;
}
Collections.reverse(Arrays.asList(levels));
return levels;
}
// 调用示例
String filePath = 'C:/Users/Administrator/Desktop/java/file.txt';
String[] levels = getLastThreeLevels(filePath);
System.out.println(Arrays.toString(levels)); // 输出:[java, Desktop, Administrator]
原文地址: https://www.cveoy.top/t/topic/ofgz 著作权归作者所有。请勿转载和采集!