在maven项目中,文件结构如下:
proj
---src
----main
----java
----Main.java
----resources
----userFile.properties
----test
----java
----Test.java
----resources
----userFile.properties
如果在程序中要读取resources目录下面的res.txt文件,需要用到以下代码:
- private Properties loadUser() throws Exception{
- if(userList == null){
- InputStream in = this.getClass().getResourceAsStream("/userFile.properties");
- if(in == null)
- throw new Exception("Can not find user file");
- else{
- userList = new Properties();
- userList.load(in);
- }
- }
- return userList;
- }
- private boolean saveUserList() throws IOException{
- if(userList == null)
- return false;
- String url = this.getClass().getResource("/userFile.properties").getFile();
- userList.store(new FileOutputStream(url), "Users Info List");
- return true;
- }
用于测试的resource 文件放在test/reources/ 目录下,用于正式运行的文件放在main/resources/ 目录下。
Maven项目中资源文件读取详解
本文详细介绍了在Maven项目中如何通过代码读取resources目录下的资源文件,并提供了资源加载和保存的实现方法。

189

被折叠的 条评论
为什么被折叠?



