java中的路径处理、左右斜杠

文章目录

      • [PathNormalizer 工具类](#PathNormalizer 工具类)

属于基础问题,也整理下。

典型场景:

获取文件路径,拿到的是 d:\data\upload 然后代码中拼接的是/,这样存到库里乱七八糟。

PathNormalizer 工具类

java 复制代码
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathNormalizer {
    
    /**
     * 统一路径分隔符为正斜杠(推荐用于存储和显示)
     */
    public static String normalizeToUnix(String path) {
        if (path == null || path.isEmpty()) {
            return path;
        }
        // 统一替换反斜杠为正斜杠
        return path.replace('\\', '/')
                   .replaceAll("/+", "/"); // 合并多个斜杠
    }
    
    /**
     * 统一为系统默认分隔符(用于文件系统操作)
     */
    public static String normalizeToSystem(String path) {
        if (path == null || path.isEmpty()) {
            return path;
        }
        // 先统一为正斜杠,再转为系统分隔符
        String normalized = normalizeToUnix(path);
        return normalized.replace('/', File.separatorChar);
    }
    
    /**
     * 安全拼接路径(所有输入先归一化)
     */
    public static String join(String base, String... parts) {
        if (base == null) {
            return null;
        }
        
        // 归一化基础路径
        String normalized = normalizeToUnix(base);
        
        // 去除末尾斜杠
        if (normalized.endsWith("/")) {
            normalized = normalized.substring(0, normalized.length() - 1);
        }
        
        // 拼接每个部分
        for (String part : parts) {
            if (part == null || part.isEmpty()) {
                continue;
            }
            // 归一化当前部分
            String normalizedPart = normalizeToUnix(part);
            // 去除开头斜杠
            if (normalizedPart.startsWith("/")) {
                normalizedPart = normalizedPart.substring(1);
            }
            normalized += "/" + normalizedPart;
        }
        
        return normalized;
    }
    
    /**
     * 转换为 Path 对象(自动处理系统分隔符)
     */
    public static Path toPath(String path) {
        if (path == null) {
            return null;
        }
        return Paths.get(normalizeToUnix(path));
    }
}
相关推荐
名字还没想好☜13 小时前
Go 并发实战:用 channel 实现 worker pool
java·数据库·后端·golang·go
人道领域13 小时前
【LeetCode刷题日记】贪心算法理论与实战:455.分发饼干最优解
java·开发语言·数据结构·算法·leetcode·贪心算法
_abab13 小时前
Java面试宝典:从基础到架构2
java·面试·架构
xin_yao_xin13 小时前
Conda 环境的 CUDA PATH 配置指南
开发语言·python·conda·cuda
he___H13 小时前
基于LCEL的联想
开发语言·python·langchain
万亿少女的梦16813 小时前
基于Spring Boot与Vue的繁星技术论坛系统设计与实现
java·spring boot·mysql·vue·系统设计
阿pin13 小时前
Android随笔-神经系统Handler
android·java·开发语言·handler
想会飞的蒲公英13 小时前
TF-IDF + 随机森林中文文本分类全链路实战:从训练脚本到 Flask API + Streamlit 前端
人工智能·pytorch·python·随机森林·分类·flask·tf-idf
布朗克16813 小时前
Go 入门到精通-09-复合类型之Map
开发语言·后端·golang·map