본문 바로가기
Java/Java

컬렉션/Map<K, V>) Properties, 설정 파일 쓰고 읽어오기

by 박채니 2022. 4. 2.

안녕하세요, 코린이의 코딩 학습기 채니 입니다.

 

개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.


컬렉션이란?

- 동일한 타입을 묶어 관리하는 자료 구조

 

컬렉션 프레임워크란?

- 리스트, 스택, 큐, 트리 등의 자료구조에 정렬, 탐색 등의 알고리즘을 구조화해 놓은 프레임워크

- 여러 개의 데이터 묶음 자료를 효과적으로 처리하기 위해 구조화된 클래스 또는 인터페이스의 모음

 

컬렉션의 특성에 따라 구분하면 크게 List<E>, Set<E>, Map<K, V>로 나뉩니다.

메모리의 입출력 특성에 따라 기존 컬렉션 기능을 확장/조합한 Stack<E>, Queue<E>도 있습니다.(사진에선 누락)

 


☞ Properties

- Hashtable 자식 클래스

- K, V가 String, String으로 고정 되어 설정 정보를 관리하는데에 최적화

 

Properties 객체 생성

Properties 참조변수 = new Properties();

Properties prop = new Properties();

Key값과 Value값이 String으로 고정 되어 있기 때문에 제네릭으로 타입 지정을 하지 않습니다.

 

메소드 사용해보기

요소 설정

// 요소 설정 setProperty
prop.setProperty("class", "hello.world.ThankyouJava");
prop.setProperty("url", "https://abc.com");
prop.setProperty("id", "abcdefg");

 

요소 가져오기

String _class = prop.getProperty("class");
String url = prop.getProperty("url");
String id = prop.getProperty("id");
		
System.out.println("class = " + _class);
System.out.println("url = " + url);
System.out.println("id = " + id);

@콘솔출력값
class = hello.world.ThankyouJava
url = https://abc.com
id = abcdefg

 

설정 파일 쓰기

//설정 파일 쓰기
try {
	prop.store(new FileWriter("test.properties"), "<<< test.properties >>>");
} catch(IOException e) {
	e.printStackTrace();
}

파일 생성

//test.properties

#<<< test.properties >>>
#Sat Apr 02 15:23:18 KST 2022
id=abcdefg
class=hello.world.ThankyouJava
url=https\://abc.com

 

설정 파일을 읽어와 Properties 객체에 담기

Properties prop = new Properties();
		
try {
	prop.load(new FileReader("test.properties"));
	System.out.println("파일 읽어오기 완료");
} catch (IOException e) {
	e.printStackTrace();
}
		
// 내용 열람
Set<String> set = prop.stringPropertyNames();
for(String key : set) {
	String value = prop.getProperty(key);
	System.out.println(key + " = " + value);
}

@콘솔출력값
파일 읽어오기 완료
id = abcdefg
class = hello.world.ThankyouJava
url = https://abc.com

prop.keySet()은 Object 타입을 리턴하기 때문에 그렇게 될 경우, Set의 제네릭 타입을 String이 아닌 Object로 변환해줘야 합니다.

keySet() 대신 stringPropertyNames()를 통해서 Key 값을 가져와 읽어온 설정파일을 Properties 객체에 담았습니다.