作用:解析配置文件并解决硬编码(在代码中写死的部分)
以下代码是通过Junit4运行的,如果没有添加Junit4 jar包会报错
推荐使用:方式一:线程方式获取类加载器
/**
* 使用当前线程的类加载器
* @throws IOException
*/
@Test
public void testThread() throws IOException {
//当前线程的类加载器
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
InputStream resourceAsStream = contextClassLoader.getResourceAsStream("db.properties");
Properties prop = new Properties();
prop.load(resourceAsStream);
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(username);
System.out.println(password);
}
方式二:传统IO流读取
/***
* 传统IO方式读取配置文件
* 这种方式存在硬编码问题,new FileInputStream("C:\\Users\\maple\\Desktop\\itsourcejava\\EE_WorkSpace\\Day27\\src\\db.properties");
* @throws IOException
*/
@Test
public void testIO() throws IOException {
InputStream fis = new FileInputStream("db.properties的路径");
Properties prop = new Properties();
prop.load(fis);
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(username);
System.out.println(password);
}
方式三:使用字节码对象读取配置文件
/**
* 使用字节码对象读取配置文件
* 此方式也不好,需要指定字节码对象ThreadProperties.class.getResourceAsStream("/db.properties");
* @throws IOException
*/
@Test
public void testClass() throws IOException {
//使用的是相对路径
InputStream resourceAsStream = ThreadProperties.class.getResourceAsStream("/db.properties");
Properties prop = new Properties();
prop.load(resourceAsStream);
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(username);
System.out.println(password);
}
方式四:使用类加载器读取配置文件
/**
* 使用类加载器读取配置文件
* 此方式也不好,需要指定字节码对象ThreadProperties.class.getClassLoader().getResourceAsStream("db.properties");
* @throws IOException
*/
@Test
public void testClassLoader() throws IOException {
InputStream resourceAsStream = ThreadProperties.class.getClassLoader().getResourceAsStream("db.properties");
Properties prop = new Properties();
prop.load(resourceAsStream);
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(username);
System.out.println(password);
}