java讀取properties檔案的方法

來源:互聯網
上載者:User

java讀取properties檔案的方法

   本文執行個體講述了java讀取properties檔案的方法。分享給大家供大家參考。具體實現方法如下:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

package com.test.demo;

import java.util.Properties;

import java.io.InputStream;

import java.io.IOException;

/**

* 讀取Properties檔案的例子

* File: TestProperties.java

*/

public final class TestProperties {

private static String param1;

private static String param2;

private static String param3;

private static String param4;

/**

* 對於以上的設定檔的路徑名,有一個容易忽視的問題,

* 那就是當你用Object.class.getClassLoader().get...的時候,

* 是都可以不用要加“/”,

* 但是不用getClassLoader().的時候是不行的,這是什麼原因呢?

* 由於這個設定檔是放在項目的src下的,在object載入的時候要加上“/”。

* 如果是將這個設定檔拷貝到類得同包下,則不需要加,

* 如果是用下面的方式讀取設定檔:

*/

static {

Properties prop = new Properties();

//InputStream in = Object.class.getResourceAsStream("/test.properties");

// 檔案在src下

//InputStream in = TestProperties.class.getClassLoader().getResourceAsStream("jdbc.properties");

// 檔案在src下

InputStream in = TestProperties.class.getResourceAsStream("jdbc.properties");

//檔案在同一個包下

try {

prop.load(in);

param1 = prop.getProperty("mysql.driverClassName").trim();

param2 = prop.getProperty("mysql.url").trim();

param3 = prop.getProperty("mysql.username").trim();

param4 = prop.getProperty("mysql.password").trim();

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* 私人構造方法,不需要建立對象

*/

private TestProperties() {

}

public static String getParam1() {

return param1;

}

public static String getParam2() {

return param2;

}

public static String getParam3() {

return param3;

}

public static String getParam4() {

return param4;

}

public static void main(String args[]){

System.out.println(getParam1());

System.out.println(getParam2());

System.out.println(getParam3());

System.out.println(getParam4());

}

}

  希望本文所述對大家的java程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.