java解析屬性文件的多種方式
1. 使用類解析屬性文件 properties是一種屬性文件,以keyvalue格式存儲內(nèi)容。Java中可以使用類來讀取這個文件,根據(jù)左邊的key獲取值。 多種解析屬性文件的方式中,解析文件的方式
1. 使用類解析屬性文件
properties是一種屬性文件,以keyvalue格式存儲內(nèi)容。Java中可以使用類來讀取這個文件,根據(jù)左邊的key獲取值。
多種解析屬性文件的方式中,解析文件的方式是統(tǒng)一的,都是通過load方法加載InputStream對象。主要是獲取InputStream對象的方式不同,實際使用中我們不一定能準確獲取properties屬性文件的絕對路徑。
2. 通過().getResourceAsStream獲取輸入流
第一種方式是通過().getResourceAsStream()來獲取在classpath路徑下的資源文件的輸入流。classPath目錄一般是web項目運行時的class文件和資源文件(xml, properties等)所在的目錄。
以下是獲取屬性文件的代碼示例:
import ;
import ;
import ;
public class PropertiesUtils {
/
* 根據(jù)key獲取屬性文件的值
*
* @param key
* @return
*/
public static String getCfgPropertiesValue(String key) {
Properties pro new Properties();
InputStream is null;
try {
is ().getResourceAsStream("");
// 讀取屬性文件
pro.load(is);
} catch (IOException e) {
();
} finally {
try {
if (is ! null) {
();
}
} catch (IOException e) {
();
}
}
return (key);
}
}
3. 通過獲取輸入流
第二種方式是通過()來獲取屬性文件的輸入流。這種方式適用于普通java項目中src下的屬性文件或者是springboot中resource中的屬性文件。
以下是獲取屬性文件的代碼示例:
import ;
import ;
import ;
public class Test5 {
public static void main(String[] args) {
("name: " getCfgPropertiesValue("name"));
}
/
* 根據(jù)key獲取的值
* @param key
* @return
*/
public static String getCfgPropertiesValue(String key) {
Properties pro new Properties();
InputStream is null;
try {
is ("");
// 讀取屬性文件
pro.load(is);
} catch (IOException e) {
();
} finally {
try {
if (is ! null) {
();
}
} catch (IOException e) {
();
}
}
return (key);
}
}
4. 使用絕對路徑解析
第三種方式是使用絕對路徑來解析屬性文件。需要提供準確的文件路徑作為參數(shù)。
以下是獲取屬性文件的代碼示例:
import ;
import ;
import ;
import ;
public class Test5 {
public static void main(String[] args) {
("name: " getPropertiesValue("D:/Workspaces/MyEclipse ", "name"));
}
public static String getPropertiesValue(String filePath, String key) {
Properties pro new Properties();
InputStream in null;
try {
// 讀取屬性文件
in new FileInputStream(filePath);
pro.load(in);
} catch (IOException e) {
();
} finally {
try {
();
} catch (IOException e) {
();
}
}
return (key);
}
}
5. 使用解析屬性文件
第四種方式是使用類解析屬性文件。這種方式適用于普通java項目src下的屬性文件或者是springboot中resource中的屬性文件。
以下是獲取屬性文件的代碼示例:
import ;
import ;
import ;
import ;
import ;
import ;
public class Test5 {
private static ResourceBundle resourceBundle ;
static{
resourceBundle ("bank_merchant_config");
String cafile ("cafile");
String store_password ("store_password");
InputStream inputStream null;
try{
inputStream new FileInputStream(cafile);
}catch (FileNotFoundException e) {
();
}
char pass[] store_password ! null ? store_() : null;
try{
keyStore ("JKS");
keyStore.load(inputStream, pass);
}catch(Exception e) {
();
}
}
}