본문 바로가기

Java SE/Properties

Java Properties example

자바 애플리케이션을 작성할 때 Properties 사용하는 예



프로그램이 실행되는 현재 디렉토리에 myapp-conf.properties 파일을 생성하는 예

import java.io.*;
import java.util.*;

public class PropertiesTest 
{

  public static void main(String[] args) {
	 
	Properties props = new Properties();
	OutputStream os = null;
 
	try {
		os = new FileOutputStream("myapp-conf.properties");

		props.setProperty("host", "localhost");
		props.setProperty("usr", "scott");
		props.setProperty("pwd", "tiger");
		props.setProperty("db", "xe");
		props.setProperty("driver", "oracle.jdbc.OracleDriver");


		props.store(os, "DB Connection Info");
 
		System.out.println("속성파일 쓰기 완료");
	} catch (IOException io) {
		io.printStackTrace();
	} finally {
		if (os != null) {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
  }
}



위의 코드를 실행하면 현재 디렉토리에 다음과 같은 속성파일이 생성된다

myapp-conf.properties

#DB Connection Info

#Wed Aug 06 13:56:17 KST 2014

db=xe

host=localhost

driver=oracle.jdbc.OracleDriver

pwd=tiger

usr=scott



위에서 생성된 속성파일에서 값을 읽어오는 예

import java.io.*;
import java.util.*;

public class PropertiesLoad {

	public static void main(String[] args) {

		InputStream in = null;
		Properties props = new Properties();
		
		try {
			in = new FileInputStream("myapp-conf.properties");
			props.load(in);
			
			String driver = (String)props.get("driver");
			String user = (String)props.get("usr");
			
			System.out.printf("user=%s, driver=%s", user, driver);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}	}
	}
}




웹프로젝트 등에서 CLASS PATH 에 저장된 속성파일을 읽어오는 예

/* /WEB-INF/classes/myapp-conf.properties에 저장된 경우 */
Properties props = new Properties();
InputStream is = null;

String propsFile = "/WEB-INF/classes/myapp-conf.properties";
is = getClass().getClassLoader().getResourceAsStream(propsFile);

props.load(is);

String driver = (String)props.get("driver"); 
String user = (String)props.get("usr"); 

System.out.printf("user=%s, driver=%s", user, driver);