Class Properties
java.lang.Object
java.util.Dictionary<K,V>
java.util.Hashtable<Object,Object>
java.util.Properties
Map 클래스를 상속받은 컬렉션의 일종. Key와 Value를 갖는다.
1 2 3 4 5 6 7 8 9 10 11 | Properties prop = new Properties(); prop.put( "서울의수도" , "서울의수도가어디있어" ); System.out.println(prop); Map<String, String> map = new HashMap<>(); map.put( "한국의수도" , "서울" ); System.out.println(map); {서울의수도=서울의수도가어디있어} {한국의수도=서울} |
해쉬맵과 흡사하나 파일입출력 기능을 지원하며 자료형은 String만 가능
● void store(OutputStream out, String comments)
● void store(Writer writer, String comments)
객체에 저장된 데이터를 파일로 출력
1 2 3 4 5 6 7 8 9 10 11 12 13 | Properties prop = new Properties(); prop.put( "서울의수도" , "서울의수도가어디있어" ); try { FileOutputStream fos = new FileOutputStream( "d:\\web\\work\\test\\data\\PropTest.propfile" ); prop.store(fos, "코멘트테스트" ); fos.close(); //경로를 명시하지 않으면 루트경로(워크스페이스\프로젝트명)에 저장된다 } catch (Exception e) { } |
● void load(InputStream inStream)
● void load(Reader reader)
맵 형태로 저장된 파일의 아스키코드를 불러와 Properties 객체에 저장
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | Properties prop = new Properties(); try { FileInputStream fis = new FileInputStream( "data\\PropTest.propfile" ); prop.load(fis); fis.close(); } catch (Exception e) { } prop.list(System.out); System.out.println( "\n" + prop.getProperty( "서울의수도" )); -- listing properties -- 서울의수도=서울의수도가어디있어 서울의수도가어디있어 |
Properties 클래스는 HashMap 과 마찬가지로 서수가 없기 때문에 각각의 값을 반복문으로 처리하려면 Iterator 를 이용한다.
예를 들어 다음과 같을때
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | Properties prop = new Properties(); prop.setProperty( "서울" , "매우많음" ); prop.setProperty( "대전" , "조금많음" ); prop.setProperty( "인천" , "많음" ); prop.setProperty( "공주" , "10만은 되려나?" ); try { FileOutputStream fos = new FileOutputStream( "data\\PropTest.propfile" ); prop.store(fos, "코멘트는 중요치 않아요~" ); fos.close(); FileInputStream fis = new FileInputStream( "data\\PropTest.propfile" ); prop.load(fis); fis.close(); } catch (Exception e) { } System.out.println(prop.values()); [많음, 매우많음, 조금많음, 10 만은 되려나?] |
여기서 이터레이터로 맵의 값을 가져오는 방법은
● Set<K> keySet() : Returns a Set view of the keys contained in this map. (HashTable 클래스의 메서드를 상속받음)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Iterator<Object> it = prop.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); String value = (String) prop.getProperty(key); System.out.println(key + " : " + value); } 인천 : 많음 서울 : 매우많음 대전 : 조금많음 공주 : 10 만은 되려나? |
아래처럼 아스키코드가 아니어도 인코딩처리 없이 사용할 수 있다.
("=" 를 기준 좌측이 key, 우측은 value)
※ 주의 : 한글은 불가능
1 2 3 4 5 6 7 8 9 10 11 12 13 | Properties prop = new Properties(); try { FileInputStream fis = new FileInputStream( "data\\PropTest.propfile" ); prop.load(fis); fis.close(); } catch (Exception e) { } System.out.println(prop); {bbs. do =com.mvc.bbs.BoardAction, ÇѱÛ=ÀÌ µÇ·Á³ª?, guest. do =com.mvc.guest.GuestAction} |
이 구문은 Servlet MVC2 패턴을 구현할 때 사용되니 숙지할 것.