java web项目获取路径_java web项目获取项目路径

注意:有时获取到的项目路径后再+“自定义路径后” 路径不可用,这时要看下项目里自定义路径是不是空文件夹,如果是空文件夹则调试和运行时文件夹不会编译到部署文件里.

1.方法一

调试时只能获取eclipse 项目未编译前的路径 不太好用

/*private static Logger logger = Logger.getLogger(BookController.class);*/@RequestMapping("/index")publicString bookHandle(HttpServletRequest servlet) {

JSONObject json=JsonResourceUtils.getJsonObjFromResource

("static/json/book_nav.json",servlet.getServletContext().getRealPath("/"));return "book";

}

2.方法 二

获取项目运行时的真实类路径

/*private static Logger logger = Logger.getLogger(BookController.class);*/@RequestMapping("/index")publicString bookHandle(HttpServletRequest servlet) {

JSONObject json=JsonResourceUtils.getJsonObjFromResource

/* 这里直接获取到了文件路径 */

(BookController.class.getClassLoader().getResource("static/json/book_nav.json").getPath());return "book";

}

3.用spring 获取运行时类路径路径

String filePath = ClassUtils.getDefaultClassLoader().getResource("").getPath();

4.其它方法

package com.demo;

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.GetMapping;

import org.springframework.web.bind.annotation.RestController;

import java.io.File;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})

@RestController

public class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class,args);

}

@GetMapping("/lujing")

public void getLujing() throws Exception{

//当前项目下路径

File file = new File("");

String filePath = file.getCanonicalPath();

System.out.println(filePath);

//当前项目下xml文件夹

File file1 = new File("");

String filePath1 = file1.getCanonicalPath()+File.separator+"xml\\";

System.out.println(filePath1);

//获取类加载的根路径

File file3 = new File(this.getClass().getResource("/").getPath());

System.out.println(file3);

//获取当前类的所在工程路径

File file4 = new File(this.getClass().getResource("").getPath());

System.out.println(file4);

//获取所有的类路径 包括jar包的路径

System.out.println(System.getProperty("java.class.path"));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值