之前在项目中使用properties资源文件,主要是客户端根据服务器端抛出的异常代码,然后客户端进行异常匹配,正好可以把这些异常代码放入properties文件中。
/**
* Created by diy_os on 2016/11/7.
*/
public class Main {
public static void main(String[] args) throws ClassNotFoundException {
Main main = new Main();
//Class cls = main.getClass();
//Class cls = Main.class;
Class cls = Class.forName("com.lios.java.Main");
ClassLoader loader = cls.getClassLoader();
InputStream in1;
/*
*运用ClassLoader 相对路径
*/
in1 = loader.getResourceAsStream("./com/lios/java/lios.properties");
//or
//in1 = loader.getResourceAsStream("com/lios/java/lios.properties");
Properties properties = new Properties();
try {
properties.load(in1);
} catch (IOException e) {
e.printStackTrace();
}
String name = properties.getProperty("name"); //通过键值取出值
System.out.println(name);
/*
*运用Class 绝对路径
*/
InputStream in2;
in2 = cls.getResourceAsStream("/com/lios/javac/diy.properties");
properties.clear(); //清空
try {
properties.load(in2);
} catch (IOException e) {
e.printStackTrace();
}
String name1 = properties.getProperty("name");
System.out.println(name1);
System.out.print("\n");
//可以通过流读取文件
File file = new File("G:/JAVA Program File/ideaworkspace/Reflect/src/com/lios/java/lios.properties");
try {
BufferedReader read = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String s;
while ((s = read.readLine()) != null) {
System.out.println(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print("\n");
//通过PropertyResourceBundle操作
try {
PropertyResourceBundle bundle = new PropertyResourceBundle(new InputStreamReader(new FileInputStream(file)));
System.out.print(bundle.getString("name"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.print("\n");
//可以自定义资源文件,然后通过流读取,再使用PropertyResourceBundle操作
String url = "G:/JAVA Program File/ideaworkspace/Reflect/resource/lios.properties";
File file1 = new File(url);
try {
PropertyResourceBundle bundle1 = new PropertyResourceBundle(new InputStreamReader(new FileInputStream(file1)));
String address = bundle1.getString("address");
System.out.println(address);
} catch (Exception e) {
e.printStackTrace();
}
}
}
getResourceAsStream默认只能加载src/下的文件,当然可以自定义资源文件夹,通过流读取文件,然后再使用PropertyResourceBundle操作。主流框架使用配置文件非常广泛,项目中恰当的使用是个不错的选择。
文件目录: