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

2020-10-19  本文已影响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"));
    }
    
}

上一篇下一篇

猜你喜欢

热点阅读