搭建項目的時候離不開配置文件,項目的配置文件通常會出現在兩種位置:
1、src->main->resources
2、磁盤文件夾中(比如D:\opt\wf\activity)
對於第一種位置,可以使用下面這種方式
ClassLoader cl = Thread.currentThread().getContextClassLoader();
InputStream inputStream = cl.getResourceAsStream("META-INF/namespace.properties");
PropertyResourceBundle pp = new PropertyResourceBundle(inputStream);
String namespace = pp.containsKey("namespace") ? pp.getString("namespace"): "";
對於第二種位置,可以使用下面這種方式
public static String getRootPath(){
File file = new File(System.getProperty("user.dir"));
String path = file.getAbsolutePath().replace('\\', '/');
path = path.substring(0, path.indexOf('/'));
return path;
}
CONFIG_FOLDER = FileUtil.getRootPath() + "/opt/wf/";
其中user.dir用於獲取當前工程路徑,getRootPath這個方法就可以返回當前工程所在的盤符。這樣我們就可以不必把盤符寫死了,系統會自動讀取當前工程所在盤符的配置文件。
通過以上這兩種方式,我們就可以遊刃有餘的玩轉配置文件了,讓我們的系統更加靈活。