day1 java基础回顾- Properties类与配置文件

Properties配置文件说明

Properties类对应.properties文件。文件内容是键值对,键值对之间使用"="或空格隔开。开头是"#"的表示注释

 

    Properties类在加载.properties文件时使用的iso8859-1的编码。所以这个文件中的中文要特殊处理:如果这个配置文件中有中文就必须要进行转义,使用native2ascii.exe命令操作:

native2ascii d:/my.properties d:/my2.properties

   

    使用Properties类中的load(InputStream) 方法可以加载配置文件,使用其中的store(OutputStream) 方法可以保存配置到指定文件。

 

    更多的信息可以看Properties类的API文档。

 加载配置文件

1 public static void testLoadProperties() throws Exception {
2     Properties properties = new Properties();
3 
4     InputStream in = new FileInputStream("E:/itcast/config.properties");
5     properties.load(in); // 加载
6     in.close();
7 
8     System.out.println(properties);
9 }

写配置文件

 1 public static void testStoreProperties() throws Exception {
 2     // 准备配置信息
 3     Properties properties = new Properties();
 4     properties.setProperty("name", "李四");
 5     properties.setProperty("age", "20");
 6 
 7     // 准备
 8     OutputStream out = new FileOutputStream("d:/my.properties");
 9     String comments = "这是我的配置文件";
10 
11     // 写出去
12     properties.store(out, comments);
13     out.close();
14 }

使用Properties类

 1 public class DBUtil {
 2     
 3     static Properties properties = new Properties();
 4     
 5     static{
 6         try {
 7             Class clazz = DBUtil.class;
 8             InputStreamReader fileReader =
 9             new InputStreamReader(clazz.getResourceAsStream("/db.properties"));
10             properties.load(fileReader);
11         } catch (IOException e) {
12             e.printStackTrace();
13         }
14     }
15     public static String getUserName(){
16         String userName =properties.getProperty("userName");
17         return userName;
18     }
19     
20     public static String getPassword(){
21         return    properties.getProperty("password");
22     }
23     public static void main(String[] args) {
24         System.out.println("用户名:"+ getUserName());
25         System.out.println("密码: "+  getPassword());
26     }
27 }

 

posted on 2016-10-09 21:18  Michael2397  阅读(165)  评论(0编辑  收藏  举报

导航