Java

[Java] properties 파일의 값 가져오기

챌인! 2023. 11. 15. 22:33

■ Properties 란?

Properties 클래스는 Hashtables의 하위 클래스이며, Hashtables를 상속 받았기 때문에 Map의 속성인 key와 values를 String 형태로 가지고 있습니다. 주로 자바에서 properties 파일은 설정정보를 저장할때 활용합니다.

 

■ 사용예제

dbConfig.properties 

properties 파일을 생성하고, 값을 key=value 형식으로 입력하여 저장합니다.

#------------------------------------------------------------------
# Load Config configuration
		

conf.db.ip = 127.0.0.1
conf.db.port = 3306
conf.db.name = test
conf.db.user = root

 

 

PropertiesTest

Properties클래스를 사용하여 properties 파일에 담겨진 정보를 읽어옵니다. 해당 코드는 다음과 같습니다.

public class PropertiesTest {

	public static void main(String[] args) {
		
		Properties config = null;
		
		try
		{
			String tmpStr = null;
			
			config = new Properties();
			config.load( new FileInputStream("./dbConfig.properties") );
		
			tmpStr = config.getProperty( "conf.db.ip" );
			System.out.println(tmpStr);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
    
}

 

 

Result

properties 파일에 저장된 db의 ip정보를 콘솔에 출력한 결과입니다.