Java属性文件就是配置文件。其中以键值对的形式存放信息。注意,每个键值对结尾没有分号
如:jdbc.properties
driverClass=com.mysql.jdbc.Driver
url=jdbc:myql:///jdbctest
username=root
password=123456
Java程序可以调用属性文件。方式为:
public class JDBCUtils {
private static final String driverClass;
private static final String url;
private static final String username;
private static final String password;
static {
//加载属性文件并解析
Properties props = new Properties();
//使用类加载器获得属性文件的输入流
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
try {
props.load(is);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("加载is失败");
}
driverClass=props.getProperty("driverClass");
url=props.getProperty("url");
username=props.getProperty("username");
password=props.getProperty("password");
}
}
步骤可以总结为:
1:编写属性文件xxx.properties;
2:获取属性文件对象:Properties props = new Properties();
3:使用类加载器获得属性文件输入流:InputStream is = 当前类.class.getClassLoader().getResourceAsStream("属性文件的路径"); 这里的路径,属性文件直接放在了eclipse的src文件夹下,当前类在包下,因为package指向的根目录也在src文件夹下,所以可以直接写文件名。
4:属性文件对象加载属性文件:props.load(is);
5:获取属性值 xxxx = props.getProperty("key");