[JAVA] 자바 프로퍼티 파일 읽기 (java properties 파일 읽기)

[JAVA] 자바 프로퍼티 파일 읽기 (java properties 파일 읽기)

자바에서 프로퍼티 읽기는 아래 코드를 사용하면 된다.

InputStream is = new FileInputStream(new File(“프로퍼티_파일경로.properties”));
Properties props = new Properties();

props.load(is);

is.close();

다만 InputStream 을 사용하기에 위 코드 그대로 사용해서는 안되고 try ~ catch 를 적용해야 한다.

전체 코드는 다음과 같다.

 

package com.bb.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

public class MainClass {

    public static void main(String[] args) {
        
        MainClass mainClass = new MainClass();
        
        String filePath = “db.properties”;
        Properties dbProp = mainClass.readProperties(filePath);
        
        System.out.println(dbProp);
    }
    
    
    public Properties readProperties(String filePath) {
        InputStream is = null;
        Properties props = null;
        File file = null;
        
        try {
            file = new File(filePath);
            if (!file.exists()) {
                System.err.println(“File not found : “ + file.getAbsolutePath());
                return null;
            }
            
            is = new FileInputStream(file);
            
            props = new Properties();
            props.load(is);
            close(is);
            
        } catch (Exception e) {
            e.printStackTrace();
            
        } finally {
            close(is);
        }
        
        return props;
    }
    
    
    public static void close(InputStream is) {
        try {
            if (is != null) {
                is.close();
            }
            
        } catch (Exception e) {
            // ignore
            
        } finally {
            is = null;
        }
    }
}