Java 代码示例,用于确定路径中包含的层级数量, 并返回第N层的名字
/**
*
* 获取路径包含的层级数量
* 通过正则表达式[\\\\/]将路径分割成不同的部分,然后通过数组长度减去文件名的部分,就可以得到路径包含的层级数量
* @param path
* @return
*/
public static int checkFileLevel(String path) {
if (StringUtils.isBlank(path)) {
return 0;
}
String[] pathParts = removeProtocolDelimiter(path).split("[\\\\/]");
int levels = pathParts.length - 1; // 减去文件名部分
// System.out.println(path + " 有 "+levels+" 级路径");
return levels;
}
/**
* 根据 层级数量 获取对应名称
* @param path
* @param targetLevel
* @return
*/
public static String getTargetFileLevelName(String path, int targetLevel) {
if (StringUtils.isBlank(path) || targetLevel <= 0) {
return "";
}
String[] pathParts = removeProtocolDelimiter(path).split("[\\\\/]");
// 确定路径中包含的层级数量
int totalLevels = pathParts.length;
int index = targetLevel >= 1 ? targetLevel : 0; // 第一层对应下标0开始
if (index <= totalLevels) {
// 返回第N层的名字
String targetName = pathParts[index];
// System.out.println("第" + targetLevel + "层的名字为: " + targetName);
return targetName;
} else {
// System.out.println("路径层级不足,无法获取第" + targetLevel + "层的名字");
return "";
}
}
/**
* 通过检查字符串中是否包含 :// 或 :\\ ,如果包含则使用正则表达式进行匹配和替换,移除这些协议分隔符
* @param filePath
* @return
*/
public static String removeProtocolDelimiter(String filePath) {
// 匹配://或:\\
Pattern pattern = Pattern.compile("://|:\\\\");
Matcher matcher = pattern.matcher(filePath);
// 将匹配到的分隔符替换为空字符串
String processedPath = matcher.replaceAll("");
return processedPath;
}