JAVA配置文件的读取

来源:互联网 发布:form表单提交数据加密 编辑:程序博客网 时间:2024/05/17 06:50
public class TestConfigFileRead {
public static void main(String[] args) throws Exception {
/**
* 使用ResourceBundle
* 优点是:可以以完全限定类名的方式加载资源后,直接的读取出来,且可以在非Web应用中读取资源文件。
* 缺点:只能加载类classes下面的资源文件且只能读取.properties文件。

*/
System.out.println("-----ResourceBundle读取配置文件的使用----START----");
ResourceBundle rb = ResourceBundle.getBundle("test");//文件无须加后缀
String name = rb.getString("name");
String age = rb.getString("age");
System.out.println(name +"\'s age is "+age); //zhangsan's age is 28
rb = ResourceBundle.getBundle("com/file/config/test1"); //如果不在根src目录下需要写出相对于根的路径
name = rb.getString("name");
age = rb.getString("age");
System.out.println(name +"\'s age is "+age);//lisi's age is 30
System.out.println("----ResourceBundle读取配置文件的使用---END----");


/**
* 使用ClassLoader
* 优点是:可以在非Web应用中读取配置资源信息,可以读取任意的资源文件信息
* 缺点:只能加载类classes下面的资源文件
*/

System.out.println("-----ClassLoader读取配置文件的使用----START----");
//使用getResourceAsStream获取输入流
InputStream is = TestConfigFileRead.class.getClassLoader().getResourceAsStream("test.properties");//根目录下
InputStream is1 = TestConfigFileRead.class.getClassLoader().getResourceAsStream("com/file/config/test1.properties");//其他的包下边
//可以获取文件的绝对路径
String filePath = TestConfigFileRead.class.getClassLoader().getResource("test.properties").getFile();
String filePath1 = TestConfigFileRead.class.getClassLoader().getResource("com/file/config/test1.properties").getFile();
System.out.println(filePath);//  D:/Workspaces/myeclipse/testjava/bin/test.properties
System.out.println(filePath1);//  D:/Workspaces/myeclipse/testjava/bin/com/file/config/test1.properties
Properties pro = new Properties();
pro.load(is);
name = pro.getProperty("name");
age = pro.getProperty("age");
System.out.println(name +"\'s age is "+age);//zhangsan's age is 28

Properties pro1 = new Properties();
pro1.load(is1);
name = pro1.getProperty("name");
age = pro1.getProperty("age");
System.out.println(name +"\'s age is "+age);//lisi's age is 30
//文件输入流获取
FileInputStream in = new FileInputStream(filePath1);
Properties pro2 = new Properties();
pro2.load(in);
name = pro2.getProperty("name");
age = pro2.getProperty("age");
System.out.println(name +"\'s age is "+age);
System.out.println("----ClassLoader读取配置文件的使用---END----");


/**
* 使用ServletContext
* 因为是用ServletContext读取文件路径,所以配置文件可以放入在web-info的classes目录中,
* 也可以在应用层级及web-info的目录中。文件存放位置具体在eclipse工程中的表现是:
* 可以放在src下面,也可放在web-info及webroot下面等。
* 因为是读取出路径后,用文件流进行读取的,所以可以读取任意的配置文件包括xml和properties。
* 缺点:不能在servlet外面应用读取配置信息
* 涉及的主要方法:
* 1. String realPath = getServletContext().getRealPath(path)//path为相对与根目录的相对路径
* 2.InputStreamReader reader =new InputStreamReader(newFileInputStream(realPath),"utf-8");//读取文件
* 3. Properties props = new Properties();
*      props.load(reader); 

*/

}


}
0 0