보뇨 다이어리

json 과 properties 파일 읽기 본문

카테고리 없음

json 과 properties 파일 읽기

보뇨 2018. 2. 18. 22:48
반응형
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
import java.io.IOException;
import java.io.FileReader;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
 
public class JsonReader {
    private String id;
    private String name;
    private JsonObject jsonObject;
    
    public void loadJson(String path) throws IOException {
        JsonParser parser = new JsonParser();
        jsonObject = (JsonObject) parser.parse(new FileReader(path));
        setVariables();
    }
    
    public void setVariables() {
        name = jsonObject.get("name").getAsString();
        id = jsonObject.get("id").getAsString();
    }
    
    public void printVariables() {
        System.out.println("-------- json 파일 읽기 --------");
        System.out.println(name);
        System.out.println(id);
        System.out.println("----------------------------");
    }
}
 
cs


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
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
 
public class PropReader {
    private String name;
    private String address;
    private Properties prop;
    private InputStream input = null;
    
    public void loadProp(String path) throws IOException {
        prop = new Properties();
        input = new FileInputStream(path);
        prop.load(input);
        setVariables();
        input.close();
    }
    
    private void setVariables() {
        name = prop.getProperty("name");
        address = prop.getProperty("address");
    }
    
    public void printVariables() {
        System.out.println("----- properties 파일 읽기 -----");
        System.out.println(name);
        System.out.println(address);
        System.out.println("----------------------------");
    }
    
    public PropReader() {}
}
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.io.IOException;
 
public class test {
    public static void main(String[] args) {
        PropReader propReader = new PropReader();
        JsonReader jsonReader = new JsonReader();
        try {
            propReader.loadProp("src\\ExampleProperties\\prop.properties");
            jsonReader.loadJson("src\\ExampleProperties\\test.json");
        } catch (IOException e) {
            e.printStackTrace();
        }
        propReader.printVariables();
        jsonReader.printVariables();
    }
}
cs


1
2
3
4
name=joonseo
address=suwon
 
(properties 파일)
cs


1
"id":123"name":"Pankaj Kumar""permanent":true"address":[{ "street":"El Camino Real""city":"San Jose""zipcode":"95014" }], "phoneNumbers":["9988664422""1234567890"], "role":"Developer" }
cs


반응형