2018년 3월 14일 수요일

[Java] Save and Load Settings with Properties (Properties를 이용해서 설정값 읽고 쓰기)



Settings.java
 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
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

public class Settings {
    
    String propertyFileName = "config.properties";
    String name;
    int age;

    public void Settings(String filename) {
        if( filename != null ) {
            propertyFileName = filename;
        }
    }
    
    public void save() {
        try {
            OutputStream output = new FileOutputStream(propertyFileName);
            Properties prop = new Properties();
            prop.setProperty("name", name);
            prop.setProperty("age", String.valueOf(age));
            prop.store(output, null);
            output.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }  
    }

    public void load() {
        try {
            InputStream input = new FileInputStream(propertyFileName);
            Properties prop = new Properties();
            prop.load(input);
            input.close();
            name = prop.getProperty("name","");
            age = Integer.valueOf(prop.getProperty("age","0"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Main.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
    public static void main(String[] args) {
        Settings setting = new Settings();
        setting.load();
        setting.name = "Zdiv";
        setting.age = 20;
        setting.save();

        Settings setting2 = new Settings();
        setting2.load();
        System.out.println("name: " + setting2.name);
        System.out.println("age: " + setting2.age);
    } 

Output:
name: Zdiv
age: 20



댓글 없음:

댓글 쓰기