Properties

: 키와 값을 String 타입으로 제한

: 애플리케이션의 옵션 정보, 데이터베이스 연결 정보, 국제화(다국어) 정보가 저장된 프로퍼티(~.properties) 파일을 읽을 때 사용

Properties properties = new Properties();

 

load() 메소드

: 프로퍼티 파일을 읽기 위해서 Properties 객체를 생성하고 load() 메소드를 호출해야 한다.

: load() 메소드는 프로퍼티 파일로부터 데이터를 읽기 위해 FileReader 객체를 매개값으로 받는다.

 

getResource() 메소드

: 프로퍼티 파일의 경로를 읽을 때 사용

 

키=값으로 구성된 프로퍼티

driver = oracle.jdbc.OracleDriver
url = jdbc:oracle:thin@localhost:1521:orcl
username = hr
password = hr

 

프로퍼티 파일로부터 읽기

package sec04.exam03_properties;

import java.io.FileReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Properties;

public class PropertiesExample {
	public static void main(String[] args) throws Exception {
		Properties properties = new Properties();
		String path = PropertiesExample.class.getResource("database.properties").getPath();
		path = URLDecoder.decode(path, "UTF-8"); //경로에 한글이 있을 경우 한글을 복원
		properties.load(new FileReader(path));
		
		String driver = properties.getProperty("driver");
		String url = properties.getProperty("url");
		String username = properties.getProperty("username");
		String password = properties.getProperty("password");
		
		System.out.println("driver: " + driver);
		System.out.println("url: " + url);
		System.out.println("username: " + username);
		System.out.println("password: " + password);
	}
}
driver: oracle.jdbc.OracleDriver
url: jdbc:oracle:thin@localhost:1521:orcl
username: hr
password: hr

+ Recent posts