java解析属性文件的多种方式
1. 使用类解析属性文件 properties是一种属性文件,以keyvalue格式存储内容。Java中可以使用类来读取这个文件,根据左边的key获取值。 多种解析属性文件的方式中,解析文件的方式
1. 使用类解析属性文件
properties是一种属性文件,以keyvalue格式存储内容。Java中可以使用类来读取这个文件,根据左边的key获取值。
多种解析属性文件的方式中,解析文件的方式是统一的,都是通过load方法加载InputStream对象。主要是获取InputStream对象的方式不同,实际使用中我们不一定能准确获取properties属性文件的绝对路径。
2. 通过().getResourceAsStream获取输入流
第一种方式是通过().getResourceAsStream()来获取在classpath路径下的资源文件的输入流。classPath目录一般是web项目运行时的class文件和资源文件(xml, properties等)所在的目录。
以下是获取属性文件的代码示例:
import ;
import ;
import ;
public class PropertiesUtils {
/
* 根据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"));
}
/
* 根据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. 使用绝对路径解析
第三种方式是使用绝对路径来解析属性文件。需要提供准确的文件路径作为参数。
以下是获取属性文件的代码示例:
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) {
();
}
}
}