Java read data from a resource file (.properties) in

In the Java project directory src, create a .properties file suffix, such as db.properties

 

As content file (key = value):

name=mk
age=123
address=China

 

Read the contents of the resource file in the program

. 1  Import java.io.File;
 2  Import a java.io.FileInputStream;
 . 3  Import java.io.FileNotFoundException;
 . 4  Import java.io.FileReader;
 . 5  Import java.io.IOException;
 . 6  Import the java.util.Properties;
 . 7  
. 8  public  class Demo01 {
 . 9    static the Properties Properties = null ;   // for reading and processing information resource file 
10    static {                               // when the class loader is performed once 
. 11      Properties = new 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"));   // find the corresponding value according to the key provided 
40      System.out.println ( "Age : "+ Properties.getProperty (" Age " ));
 41 is      System.out.println (" address: "+ Properties.getProperty (" address " ));
 42 is    }
 43 is }

 

Results of the

name: mk
age: 123
address: China

 

Guess you like

Origin www.cnblogs.com/Satu/p/11079745.html