应用场景:
应用程序经常会使用到一些配置文件,例如如下数据库连接的配置文件 connect.txt文件
driver=org.postgresql.Driver
url=jdbc:postgresql://172.23.185.81:5435/student
uid=postgres
pwd=111
程序如何读取配置文件呢?
java中getResourceAsStream有以下定义
-
Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object's class loader.
结合Properties,可以很便捷的获取上述配置文件的读取和处理
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ResourceTest {
private static String m_strClassDrive;
private static String m_strUrl;
private static String m_strUser;
private static String m_strPassword;
private final static String FILE_PATH_NAME = "/pointservice/connect.txt";
public static void main(String[] args) {
InputStream in = ResourceTest.class.getResourceAsStream(FILE_PATH_NAME);
if (null == in) {
System.out.println("文件获取失败!");
return;
}
Properties props = new Properties();
try {
props.load(in);
m_strClassDrive = props.getProperty("driver");
m_strUrl = props.getProperty("url");
m_strUser = props.getProperty("uid");
m_strPassword = props.getProperty("pwd");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(m_strClassDrive);
System.out.println(m_strUrl);
System.out.println(m_strUser);
System.out.println(m_strPassword);
}
}
其中,注意将配置文件放在于程序的class文件下,以class文件作为根目录访问。