美文网首页
Java获取类加载路径和项目根路径

Java获取类加载路径和项目根路径

作者: 爱恨_交加 | 来源:发表于2020-10-19 11:46 被阅读0次
    package com.example.demo;
    
    import java.io.File;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
    import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
    @RestController
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    
        @RequestMapping("path")
        public void getPath() throws Exception{
            //项目路径--第一种 
            // output: G:\repository\editor\sts4\github\my\demo
            File file = new File("");
            String filePath = file.getCanonicalPath();
            System.out.println(filePath);
            //项目路径--第二种 
            // output: G:\repository\editor\sts4\github\my\demo
            System.out.println(System.getProperty("user.dir"));
            
            //类加载的根路径
            // output: G:\repository\editor\sts4\github\my\demo\target\classes
            File file3 = new File(this.getClass().getResource("/").getPath());
            System.out.println(file3);
     
            //类所在的工程路径
            // output: G:\repository\editor\sts4\github\my\demo\target\classes\com\example\demo
            File file4 = new File(this.getClass().getResource("").getPath());
            System.out.println(file4);
    
            //获取所有的类路径 包括jar包的路径
            // output: G:\repository\editor\sts4\github\my\demo\target\classes;E:\Maven\ ...
            System.out.println(System.getProperty("java.class.path"));
        }
        
    }
    
    

    相关文章

      网友评论

          本文标题:Java获取类加载路径和项目根路径

          本文链接:https://www.haomeiwen.com/subject/alskmktx.html