정의
- 키-값 쌍으로 이루어진 데이터(.properties)를 저장하고 관리하는 데 사용되는 클래스
- Properties 객체는 key=value의 쌍으로 데이터를 저장하며 키와 값 모두 문자열로 구성
Properties properties = new Properties();
properties.put("key1", "value1");
properties.put("key2", "value2");
String value1 = properties.getProperty("key1");
주요 메소드
- get(key) = 해당 key에 대한 value 반환 (반환 타입 = Object)
- getProperty(key) = 해당 key에 대한 value 반환 (반환 타입 = String)
- remove(key) = 해당 key에 대한 데이터 제거
- load(InputStream) = 입력 스트림에서 데이터를 읽고 읽어온 데이터를 저장
- store(OutputStream, "comment") = 데이터들을 출력 스트림에 저장
- stringPropertyNames() = 데이터들의 key들을 Set로 반환
- list(System.out) = 모든 데이터들을 키와 값을 나열하여 출력
- put() = 데이터(키=값) 추가
- putAll(Map) = 해당 Map의 데이터들을 모두 추가
- clear() = 모든 데이터 제거
- size() = 데이터 개수 반환
.properties 파일에서 데이터 로드 및 저장
// 파일에서 로드
Properties properties = new Properties();
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("config.properties");
// InputStream에서 로드
properties.load(inputStream);
// 방법1
String value = properties.getProperty("key")
// 방법2
String value = (String) properties.get("key")
// 파일에 저장
properties.store(new FileOutputStream("config.properties"), "Comments");
- 파일 혹은 InputStream을 통해 데이터를 로딩하며 파일 혹은 OutputStream을 통해 데이터를 저장함
- getResource()와 getResourceAsStream()을 통해 src/main/resources으로 접근하여 scr/main/resources를 기준으로 상대 경로로 파일을 불러올 수 있음
※ getResource()는 URL 객체, getResourceAsStream()는 InputStream 객체를 반환함
'Java' 카테고리의 다른 글
java.io.File (0) | 2023.12.20 |
---|---|
java.io.InputStream & OutputStream (0) | 2023.12.20 |
java.io.Reader & Writer (0) | 2023.12.20 |
BufferedReader/BufferedWriter (0) | 2023.12.19 |
java.net.HttpURLConnection (0) | 2023.12.19 |
댓글