Java 從資源文件(.properties)中讀取數據


在Java工程目錄src下,創建一個后綴為.properties的文件,例如db.properties

 

文件中的內容如下(鍵=值):

name=mk
age=123
address=China

 

在程序中讀取資源文件中的內容

 1 import java.io.File;
 2 import java.io.FileInputStream;
 3 import java.io.FileNotFoundException;
 4 import java.io.FileReader;
 5 import java.io.IOException;
 6 import java.util.Properties;
 7 
 8 public class Demo01 {
 9   static Properties properties = null;  // 用於讀取和處理資源文件中的信息
10   static {                              // 類加載的時候被執行一次
11     properties = new Properties();
12     // 加載方式一
13     try {
14       properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
15     } catch (IOException e) {
16       e.printStackTrace();
17     }
18     
19     // 加載方式二
20 //    try {
21 //      properties.load(new FileInputStream(new File("src/db.properties")));
22 //    } catch (FileNotFoundException e) {
23 //      e.printStackTrace();
24 //    } catch (IOException e) {
25 //      e.printStackTrace();
26 //    }
27     
28     // 加載方式三
29 //    try {
30 //      properties.load(new FileReader(new File("src/db.properties")));
31 //    } catch (FileNotFoundException e) {
32 //      e.printStackTrace();
33 //    } catch (IOException e) {
34 //      e.printStackTrace();
35 //    }
36   }
37   
38   public static void main(String[] args) {
39     System.out.println("name: " + properties.getProperty("name"));  // 根據提供的鍵找到對應的值
40     System.out.println("age: " + properties.getProperty("age"));
41     System.out.println("address: " + properties.getProperty("address"));
42   }
43 }

 

執行結果

name: mk
age: 123
address: China

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM