有時候,寫了一個配置文件,需要知道讀出來的內容對不對,我們需要測試一下,看看讀出來的跟我們要的是不是一樣。這里寫了一個工具類,用來讀取配置文件里面的內容。
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://m.survivalescaperooms.com/liuhongfeng/p/4176224.html
本文版權歸作者和博客園共有,但未經作者同意轉載必須保留以上的聲明且在放在文章頁面明顯位置。謝謝合作。
新聞熱點
疑難解答