首页 > 代码库 > 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
package com.suyang.properties;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
 
public class TestProperties {
 
    private final String PATH = "test.properties";
    private static Properties props = new Properties();
 
    static {
        try {
            props.load(new FileInputStream("test.properties"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public String getProperty(String name) {
        return props.getProperty(name);
    }
 
    public void setProperty(String name, String value) {
        props.setProperty(name, value);
    }
     
    public void save(){
        OutputStream fos = null;
        try {
            fos = new FileOutputStream(PATH);
            props.store(fos, "");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        finally{
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}