Java读取resource文件/路径的几种方式

Java读取resource文件/路径的几种方式

1. 说明

该文章转载自 https://blog.csdn.net/oschina_40188932/article/details/78833754?utm_source=blogxgwz0,写的很好 感谢解决我的需求,特此记录一下

2. 实现

在这里插入图片描述

2.1 方式一

//获取文件路径
String fileName = this.getClass().getClassLoader().getResource("文件名").getPath();
String fileUtl = this.getClass().getResource("文件名").getFile();

在项目打成jar后的情况下getPath()与getFile()返回参数及用法的基本相同具体差异大研究)
示例路径结果:/E:/idea_work/sofn-qry-web/target/classes/CityJson.js

2.2 方式二

File directory = new File("");//参数为空
String courseFile = directory.getCanonicalPath()//标准的路径 ;
String author =directory.getAbsolutePath()//绝对路径;

在jdk1.1后就有了此方法获取文件路径的方式存在了)
示例路径结果:E:\idea_work\sofn-qry-web

2.3 方式三

在web.xml配置如下代码

<context-param>  
    <param-name>webAppRootKey</param-name>   
    <param-value>evan.webapp</param-value>  
</context-param>  
<listener>   
    <listener-class>org.springframework.web.util.WebAppRootListener</listener-class>   
</listener>

其中param-value的值可以随便赋值,只要保证同一个tomcat下不同项目的param-value不重复即可,调用如下

System.getProperty("evan.webapp");
//获取的值类似E:\develop_tools\apache-tomcat-7.0.59\webapps\bookMobile
posted @ 2018-10-29 23:57  风中追风_lonely  阅读(5958)  评论(0编辑  收藏  举报