java 如何读取src根目录下的属性文件
2024-09-04 07:08:50
在java项目中,如何获取src根目录下的属性文件/资源文件呢?
有如下三种方式:
方式一:
InputStream in = Test.class
.getResourceAsStream("/env.properties");
URL url = Test.class.getResource("<span style="color: #000000;">/</span>env.properties") ;
说明:env.properties文件在src的根目录下,文件名前有斜杠
方式二:
InputStream in = Test.class.getClassLoader()
.getResourceAsStream("env.properties");
URL url = Test.class.getClassLoader().getResource("env.properties") ;
方式三:
InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("ExcelModeMappingl.xml");
示例:
private Properties readConfig(){
InputStream in = this.getClass().getResourceAsStream("/config.properties");
// String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
// int lastIndex = path.lastIndexOf(File.separator) + 1;
// path = path.substring(0, lastIndex);
// File configFile = new File(path + "configration.properties");
// InputStream in = null;
// try
// {
// in = new FileInputStream(configFile);
// }
// catch (FileNotFoundException e)
// {
// e.printStackTrace();
// } Properties props = new Properties();
InputStreamReader inputStreamReader = null;
try
{
inputStreamReader = new InputStreamReader(in, "UTF-8");
props.load(inputStreamReader);
}
catch (Exception e)
{
e.printStackTrace();
}
return props;
}
config.properties在src/main/resources目录下
注释掉的部分是读取jar包平级目录下的配置文件。有时需要把配置文件放在jar包外面方便配置,因此需要读取jar包外的配置文件。
本地读取资源文件
java类中需要读取properties中的配置文件,可以采用文件(File)方式进行读取:
1 File file = new File("src/main/resources/properties/basecom.properties");
2 InputStream in = new FileInputStream(file);
当在eclipse中运行(不部署到服务器上),可以读取到文件。
服务器(Tomcat)读取资源文件
采用流+Properties
当工程部署到Tomcat中时,按照上边方式,则会出现找不到该文件路径的异常。经搜索资料知道,Java工程打包部署到Tomcat中时,properties的路径变到顶层(classes下),这是由Maven工程结构决定的。由Maven构建的web工程,主代码放在src/main/java路径下,资源放在src/main/resources路径下,当构建为war包的时候,会将主代码和资源文件放置classes文件夹下:
并且,此时读取文件需要采用流(stream)的方式读取,并通过JDK中Properties类加载,可以方便的获取到配置文件中的信息,如下:
InputStream in = this.getClass().getResourceAsStream("/properties/basecom.properties");
Properties properties = new Properties();
properties.load(in);
properties.getProperty("property_name");
其中properties前的斜杠,相对于调用类,共同的顶层路径。
最新文章
- git快速get
- 使用ssh连接远程主机
- WebServiceCaller
- http://wenku.baidu.com/link?url=UGoPtZviipHzi5SDIlGx6hPFWAHTPLFXcZ7ieD15JMd81DEHqjehvphVMhqELmOK4qXR74dTT9nW8VBoApBc7Kfb1ZWrNF_i24fY1YRHVki
- 移动周报:十款最实用的Android UI设计工具
- 动态树LCT小结
- 在 VS2008 下操作 Excel 的方法总结
- android分割线
- 接收串口数据0x00 strlen函数会截断
- 一张图总结Google C++编程规范(Google C++ Style Guide)
- Ant 随想
- 1.JAVA WEB 笔记中文乱码
- 【js高程学习笔记】关于变量值和函数参数
- solidworks的工程图模板文件和图纸格式文件
- ssh连接服务器失败解决记录
- 在 .NET项目中使用 Redis(2018.10.16)
- Visual Studio 2015 激活码
- 51nod1237 最大公约数之和 V3
- Codeforces 268B - Buttons
- MATLAB程序控制结构