2016-09-09 3 views
0

속성 파일이 있습니다.자바 속성 파일에 액세스하는 방법

#My properties file 
config1=first_config 
config2=second_config 
config3=third_config 
config4=fourth_config 

작은 Java 응용 프로그램에서 등록 정보 파일을로드하는 클래스가 있습니다. 이 클래스의 메서드 내에서 각 속성에 액세스하려고하면 잘 작동합니다.

public class LoadProperties { 
    public void loadProperties() { 
    Properties prop = new Properties(); 
    InputStream input = null; 
    try { 
     input = new FileInputStream("resources/config.properties"); 
     prop.load(input); 

    } catch (Exception e) { 
     System.out.println(e); 
    } 
    } 
} 

나는 그 클래스의 메서드를 다른 클래스의 메서드에서 호출하고 있습니다.

public class MyClass { 
    public void myMethod() { 
    LoadProperties lp = new LoadProperties(); 
    lp.loadProperties(); 
    /*..More code...*/ 
    } 
} 

은 어떻게 MyClass 클래스의 myMethod 방법의 속성을 액세스합니까? prop.getProperty("[property_name]")을 입력하려고했는데 작동하지 않습니다.

아이디어가 있으십니까? 이 속성을 액세스하는 방법이 될 것이라고 가정합니다. 변수를 loadProperties 클래스의 변수에 저장하고 변수를 반환 할 수는 있지만 위에서 설명한 방법에 액세스 할 수 있다고 생각했습니다.

답변

2

LoadProperties 클래스를 변경하여 속성을로드하고로드 된 속성을 반환하는 메서드를 추가 할 수 있습니다.

public class LoadProperties { 
    Properties prop = new Properties(); 
    public LoadProperties() { 
     try (FileInputStream fileInputStream = new FileInputStream("config.properties")){ 
      prop.load(fileInputStream); 
     } catch (Exception e) { 
      System.out.println(e); 
     } 
    } 

    public Properties getProperties() { 
     return prop; 
    } 
} 

그런 다음, 당신은`FileInputStream`을 닫지 마십시오 질문 코드와 동일이

public class MyClass { 
    public void myMethod() { 
     LoadProperties loadProperties = new LoadProperties(); 
     System.out.println(loadProperties.getProperties().getProperty("config1")); 
    } 
} 
+0

처럼 사용합니다. 완료되면 스트림을 닫아야합니다. [try-with-resources] (https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)를 사용하는 것이 더 바람직합니다. – Andreas

+1

나는 원래 게으른 질문에 대해서만 대답하고 있었다. System.out.println을 사용하는 대신 적절한 예외 처리를 구현해야합니다. – Guenther

관련 문제