Java获取Window和Linux系统的项目路径

不啰嗦,直接复制工具类

import java.io.File;

/**
 * 在windows和linux系统下均可正常使用
 * Create by [email protected] 2018/6/6/006 14:51
 */
public class ProjectPath {

    public final static String classPath = System.getProperty("user.dir");//获取项目的根路径

    /**
     * 项目根目录
     */
    public static String getRootPath() {
        return RootPath("");
    }

    /**
     * 自定义追加路径
     */
    public static String getRootPath(String u_path) {
        return RootPath("/"+u_path);
    }

    /**
     * 私有处理方法
     */
    private static String RootPath(String u_path){
        String rootPath = "";
        //windows下
        if("\\".equals(File.separator)){
            //System.out.println(classPath);
            rootPath = classPath+u_path;
            rootPath = rootPath.replaceAll("/", "\\\\");
        }
        //linux下
        if("/".equals(File.separator)){
            //System.out.println(classPath);
            rootPath = classPath+u_path;
            rootPath = rootPath.replaceAll("\\\\", "/");
        }
        return rootPath;
    }

    //更多扩展方法任你发挥

}

使用方法

//自定义追加路径并格式化
System.out.println(ProjectPath.getRootPath("userImg/test.txt"));
//获取根目录
System.out.println(ProjectPath.getRootPath());

猜你喜欢

转载自blog.csdn.net/yueshutong123/article/details/80596318
今日推荐