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


    【本文版权归微信公众号"代码艺术"(ID:onblog)所有,若是转载请务必保留本段原创声明,违者必究。若是文章有不足之处,欢迎关注微信公众号私信与我进行交流!】

    不啰嗦,直接复制工具类

    /**
     * 在windows和linux系统下均可正常使用
     * Create by yster@foxmail.com 2018/6/6/006 14:51
     */
    public class PathUtil {
        //获取项目的根路径
        public final static String classPath;
    
        static {
            //获取的是classpath路径,适用于读取resources下资源
            classPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        }
    
        /**
         * 项目根目录
         */
        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("/", "\\");
                if (rootPath.substring(0, 1).equals("\")) {
                    rootPath = rootPath.substring(1);
                }
            }
            //linux下
            if ("/".equals(File.separator)) {
                //System.out.println(classPath);
                rootPath = classPath + u_path;
                rootPath = rootPath.replaceAll("\\", "/");
            }
            return rootPath;
        }
    
        //更多扩展方法任你发挥
    
    }
    

    使用方法

    【本文版权归微信公众号"代码艺术"(ID:onblog)所有,若是转载请务必保留本段原创声明,违者必究。若是文章有不足之处,欢迎关注微信公众号私信与我进行交流!】

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

    注意

    在使用System.getProperty("user.dir")时:

    如果是在IDE中启动,则获得的路径为D:xxxxprojectName,包括项目名;

    如果是以Jar包方式启动,得到该jar包所在的路径。如project.jar在D:xxxx下,获得的路径就是D:xxxx

    但是如果是以war包方式启动获得的是:D:apache-tomcat-9.0.7in

    所以此方法适合不依赖Tomcat容器(或者内嵌Tomcat如SpringBoot)的项目。

    版权声明

    【本文版权归微信公众号"代码艺术"(ID:onblog)所有,若是转载请务必保留本段原创声明,违者必究。若是文章有不足之处,欢迎关注微信公众号私信与我进行交流!】

  • 相关阅读:
    【转】浏览器兼容性问题汇总
    【转】sql server数据库操作大全——常用语句/技巧集锦/经典语句
    如何在数据库中导入excel文件内的数据
    【总算解决了】A network-related or instance-specific error occurred while establishing a connection to SQL Server
    【转】JS容器拖拽效果,并通过cookie保存拖拽各容器的所在位置
    【转】SQL多条件模糊查询解决方案-存储过程
    ASP搜索查询
    解决SQL Server 阻止了对组件 'Ad Hoc Distributed Queries' 的 STATEMENT 'OpenRowset/OpenDatasource' 的访问
    简单鼠标跟随代码
    【JS】jquery通知插件toastr
  • 原文地址:https://www.cnblogs.com/onblog/p/13043392.html
Copyright © 2020-2023  润新知