有时候,写了一个配置文件,需要知道读出来的内容对不对,我们需要测试一下,看看读出来的跟我们要的是不是一样。这里写了一个工具类,用来读取配置文件里面的内容。
1.新建一个java工程,导入需要的jar包,新建一个配置文件 如下图:
2.配置文件的内容:
1 driver=com.MySQL.jdbc.Driver2 url=jdbc:mysql://localhost:3306/csdn3 user=root4 pwd=1234565 initsize=16 maxactive=17 maxwait=50008 maxidle=19 minidle=1
3.读取配置文件工具类:
1 package com.VEVb.daliu_it; 2 3 import java.io.FileInputStream; 4 import java.util.Properties; 5 6 /** 7 * 读取配置文件 8 * @author daliu_it 9 */10 public class GetProperties {11 public static void getProperties() {12 try {13 // java.util.Properties14 /*15 * Properties类用于读取properties文件 使用该类可以以类似Map的形式读取配置 文件中的内容16 * 17 * properties文件中的内容格式类似: user=openlab 那么等号左面就是key,等号右面就是value18 */19 Properties prop = new Properties();20 21 /*22 * 使用Properties去读取配置文件23 */24 FileInputStream fis = new FileInputStream("config.properties");25 /*26 * 当通过Properties读取文件后,那么 这个流依然保持打开状态,我们应当自行 关闭。27 */28 prop.load(fis);29 fis.close();30 System.out.println("成功加载完毕配置文件");31 32 /*33 * 当加载完毕后,就可以根据文本文件中 等号左面的内容(key)来获取等号右面的 内容(value)了34 * 可以变相的把Properties看做是一个Map35 */36 String driver = prop.getProperty("driver").trim();37 String url = prop.getProperty("url").trim();38 String user = prop.getProperty("user").trim();39 String pwd = prop.getProperty("pwd").trim();40 System.out.println("driver:" + driver);41 System.out.println("url:" + url);42 System.out.println("user:" + user);43 System.out.println("pwd:" + pwd);44 45 } catch (Exception e) {46 e.printStackTrace();47 }48 }49 }
4.测试类:
1 package com.daliu_it.test; 2 3 import java.sql.SQLException; 4 5 import org.junit.Test; 6 7 import com.VEVb.daliu_it.GetProperties; 8 9 public class testCase {10 11 /**12 * 获得配置文件13 * @throws SQLException14 */15 @Test16 public void testgetProperties() throws SQLException {17 GetProperties poperties=new GetProperties();18 poperties.getProperties();19 }20 }
5.效果图:
原文作者:daliu_it博文出处:http://www.VEVb.com/liuhongfeng/p/4176224.html
本文版权归作者和博客园共有,但未经作者同意转载必须保留以上的声明且在放在文章页面明显位置。谢谢合作。
新闻热点
疑难解答