개발/Java

[Java] 자바 - 컬렉션 - Properties

하더 2022. 9. 25. 17:32

 

< Properties >

 

- Map계열로 Key와 Value를 세트로 저장함

- Key와 Value 모두 String형을 다룸

[ 표현법 ] Properties 객체 이름 = new Properties();

 

[ 용도 ]

- 파일 입출력을 위해 사용

- Key + Value 세트로 파일에 기록하거나, 파일로부터 읽어오는 용도로 많이 사용됨

- 파일확장자 : .properties

- 변경이 잦지 않은 설정파일이나, 해당 프로그램이 기본적으로 가져야 할 정보들을 담는 파일로 활용

 

Properties prop = new Properties();
    // String, String형으로 담기
    prop.setProperty("List", "ArrayList");
    prop.setProperty("Set", "HashSet");
    prop.setProperty("Map", "HashMap");

    Properties inputProp = new Properties(); // properties값을 받아줄 변수

    try {
        // 출력
        prop.store(new FileOutputStream("test.properties"), "Properties Test");
        // store(OutputStream os, String Comments) : 파일을 기록할 때 쓰는 메소드
        // key = value 형태로 파일이 출력됨

        // 입력
        inputProp.load(new FileInputStream("test.properties"));
        // load(InputStream is) : 파일로부터 읽어올 때 쓰이는 메소드
        System.out.println(inputProp.getProperty("List")); // get(키)를 넣어 Value값을 반환받음
        
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}