Java读取配置文件方法及文件路径注意事项

一、方法请见代码中的注释说明,需要注意的就是对于文件路径的读取方式,不同的方法,对路径的解释是不一样的。

 1 package com.yard39.ProperTiesFileReader.Test;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileNotFoundException;
 5 import java.io.IOException;
 6 import java.io.InputStream;
 7 import java.util.Properties;
 8 
 9 public class PropertiesFileReader {
10 
11     // Test method
12     public static void main(String[] args) {
13         Properties p = new Properties();
14         InputStream is;
15         try {
16             String filepath1 = "src/config/config.properties";
17             String filepath2 = "/config/config.properties";
18             String filepath3 = "config/config.properties";
19             // 1、利用文件流方法,注意路径自项目根目录下开始读取,不用"/"
20             // is = new FileInputStream(filepath1);
21             // 2、利用class.getResourceAsStream()方法,注意路径自src下读取,需要用"/"
22             // is = PropertiesFileReader.class.getResourceAsStream(filepath2);
23             // 3、利用class.getClassLoader().getResourceAsStream(),注意路径自src下读取,不用"/"
24             is = PropertiesFileReader.class.getClassLoader().getResourceAsStream(filepath3);
25             p.load(is);
26             is.close();
27             String value = p.getProperty("jdbc.connection.username");
28             System.out.println(value);
29         } catch (FileNotFoundException e) {
30             e.printStackTrace();
31         } catch (IOException e) {
32             e.printStackTrace();
33         }
34     }
35 }

二、文件路径总结

(后补)

posted on 2015-06-25 12:31  yard39  阅读(673)  评论(0编辑  收藏  举报