2017-09-24 3 views
-1

속성을 래핑하고 파일 I/O 작업을 숨기는 클래스를 만들고 싶습니다. 나는 아래에 요약 된 코드를 제안했다. 클래스 경로 외부의 고정 된 위치에있는 파일에서 속성을 읽으려고합니다. 또한 같은 파일에 속성을 쓰는 방법도 있습니다.속성을 래핑 할 클래스 만들기

// 
/* Defines key properties of the iFlag application. 
    * Methods read and write properties. 
*/ 

public class ClientProperties { 
    private Properties props; 
    private static String xPanelSizeStg = "32"; 
    private static int xPanelSize = 32; 
    private static String configFilename = "/home/myname/config/client_config.properties"; 

    public ClientProperties() { 
     props = new Properties(); 
    } 


    /** 
    * Reads properties from file 
    * Reads the current properties object from file. 
    * The file is stored in /home/mimibox/config/flag_config.properties 
    */    

    public Properties readPropertiesFromFile(){ 
     // create and load default properties 
     InputStream input = null; 
     logger.trace("Read flag config properties."); 
     try { 
      input = new FileInputStream(configFilename); 
      //load a properties file from class path, inside static method  
      props.load(input); 
      //get the property values and save 
      xPanelSizeStg = props.getProperty("xPanelsize","32"); 
      yPanelSizeStg = props.getProperty("yPanelsize", "32"); 
     } 
     catch (IOException ex) { 
      logger.error("Could not open config file" + configFilename,ex); 
     } 
     finally{ 
      if(input!=null){ 
       try { 
        input.close(); 
       } 
       catch (IOException e) { 
       logger.error("Could not close config file" + configFilename,e); 
       } 
      } 
     } 
     return props; 
    } 
    /** 
    * Writes properties to file 
    * Writes the current properties object to file. 
    * The file is stored in /home/mimibox/config/flag_config.properties 
    */ 

    public void writePropertiesToFile() { 
    //saves the current properties to file. Overwrites the existing properties. 
    Properties props = new Properties(); //a list of properties 
    OutputStream outStrm = null; 
    logger.info("Writing default flag config properties."); 
       System.out.println("Panel size x = " + xPanelSizeStg); 
    try { 
     outStrm = new FileOutputStream(configFilename); 
     // set the properties values 
     props.setProperty("xPanelsize", xPanelSizeStg); 
     props.setProperty("yPanelsize", yPanelSizeStg); 
     // save properties to file, include a header comment 
     props.store(outStrm, "This is the Server configuration file"); 

     } catch (IOException io) { 
      logger.error("The file :{0} could not be opened", configFilename,io); 
     } finally { 
      if (outStrm!= null) { 
       try { 
        outStrm.close(); 
       } catch (IOException e) { 
        logger.error("The file :{0} could not be closed", configFilename, e); 
       } 
      } 
     } 
    } 
} 

읽기 및 쓰기 방법이 작동합니다. 작동하지 않는 것은 속성 값을 변경하고 저장하는 것입니다. 아래의 데모 코드는 속성 파일을 성공적으로 읽고 XPanelsize에 대한 올바른 값을 표시합니다. 그런 다음 해당 값을 변경하고 속성을 파일에 쓰려고 시도합니다. xPanelsize의 새 값 64는 파일에 기록되지 않습니다.

public static void main(String[] args) { 
    Properties props; 
    ClientProperties p = new ClientProperties(); 
    props = p.readPropertiesFromFile(); 
    String txt = props.getProperty("xPanelsize"); 
     System.out.println("Panel size x = " + txt); 
    p.setProperty("xPanelsize","64"); //method not found error 
    p.writePropertiesToFile(); 

그래서 Property.setProperty() 메서드를 사용하여 속성 값을 설정하고 싶습니다. 그렇게하면 변경된 속성이 파일에 기록되지 않습니다. 하나 이상의 Property 인스턴스가 있고 다른 인스턴스는 볼 수 없기 때문에이 인스턴스를 볼 수 있습니다. 내가 원하는 것을 얻기 위해 내장 된 Properties 클래스를 확장해야한다고 생각하지만, 모든 작업을 수행하는 방법을 잘 모르겠습니다.

나는 인터넷에서 등록 정보를 사용하는 예제를 많이 보았습니다. 내가 찾지 못한 것은 클래스에서 관련된 파일 I/O를 숨기는 예제입니다. 나는 그것을 어떻게 할 것이냐 ??

+0

1. Yoy는 p.setProperty() 대신 props.setProperty()를 호출해야합니다. 2. U는 이전 값으로 writePropertiesToFile() 메소드에서 동일한 키 "xPanelsize"를 대체하므로 반영되지 않습니다. –

+0

'java.util.ResourceBundle'을 알고 있습니까? – EJP

+0

모호합니다. 사용하기에 충분하지 않습니다. – dazz

답변

0

'props'객체에 대한 getter를 만들어야합니다.

public Properties getProps() 
{ 
    return props; 
} 

그리고 당신은 이런 식으로 호출 할 수 있습니다 : 당신은 속성 클래스의 아이들이, 당신은 사용해야 할 것이다 ClientProperties 클래스를 만들 계획하는 경우,

p.getProps().setProperty("key", "value"); 

또는 '확장 '를 사용하여 호출 할 수 있습니다.

p.setProperty("key", "value"); 

이 경우에는 클래스 필드에 Properties 객체가 필요하지 않습니다.

+0

좋아, 내 매우 제한된 지식을 기반으로, 속성 확장 최고의 옵션과 같은 소리. 나는 변화를 가도록 갈 것이다. – dazz

+0

이것이 작업 코드를 작성하는 데 필요한 정보를 주었기 때문에 대답으로 썼습니다. 다른 사람들의 이익을 위해 제 대답에 작동 코드가 제공됩니다. – dazz

0

귀하의 예를 들어 보겠습니다.

첫째, 당신은이처럼 writePropertiesToFile 방법에서 다시 속성을 편집 할 필요가 없습니다

public void writePropertiesToFile() { 
    // saves the current properties to file. Overwrites the existing properties. 
    // Properties props = new Properties(); // a list of properties 
    OutputStream outStrm = null; 
    logger.info("Writing default flag config properties."); 
    logger.debug("Panel size x = " + xPanelSizeStg); 
    try { 
     outStrm = new FileOutputStream(configFilename); 
     // set the properties values 
     //props.setProperty("xPanelsize", xPanelSizeStg); 
     //props.setProperty("yPanelsize", yPanelSizeStg); 
     // save properties to file, include a header comment 
     props.store(outStrm, "This is the Server configuration file"); 

    } catch (IOException io) { 
     logger.error("The file :{0} could not be opened", configFilename, io); 
    } finally { 
     if (outStrm != null) { 
      try { 
       outStrm.close(); 
      } catch (IOException e) { 
       logger.error("The file :{0} could not be closed", configFilename, e); 
      } 
     } 
    } 
} 

그런 다음, 당신은 단지 클래스의 전역 변수 -props-를 사용하여 setProperty 메소드를 만듭니다. xPanelsize의 값은 응용 프로그램을 실행 한 후 변경해야

enter image description here

:

private void setProperty(String key, String value) { 
    this.props.setProperty(key, value); 
} 

은 속성 파일은 아래 이미지처럼 보인다면.

public static void main(String[] args) { 
    Properties props = null; 
    ClientProperties p = new ClientProperties(); 
    props = p.readPropertiesFromFile(); 
    String xPanelsize = props.getProperty("xPanelsize"); 
    System.out.println("Panel size x = " + xPanelsize); 
    p.setProperty("xPanelsize", "64"); // method not found error 

    p.writePropertiesToFile(); 

    props = p.readPropertiesFromFile(); 
    xPanelsize = props.getProperty("xPanelsize"); 
    System.out.println("So, now the Panel size x = " + xPanelsize); 
} 

디버그 메시지는, enter image description here

속성 파일 내용 은 다음과 같습니다 덕분에 너무

package stackoverflow; 

import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.util.Properties; 
import java.util.logging.Level; 

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 

/* Defines key properties of the iFlag application. 
* Methods read and write properties. 
*/ 

public class ClientProperties { 
    Logger logger = LoggerFactory.getLogger(ClientProperties.class.getSimpleName()); 
    private Properties props; 
    private String xPanelSizeStg; 
    private String yPanelSizeStg; 
    private int xPanelSize; 
    private int yPanelSize; 
    // private static String configFilename = 
    // "/home/myname/config/client_config.properties"; 
    private static String configFilename = "resource/client_config.properties"; 

    public ClientProperties() { 
     props = new Properties(); 

     xPanelSizeStg = "32"; 
     yPanelSizeStg = "32"; 
     xPanelSize = 32; 
     yPanelSize = 32; 
    } 

    /** 
    * Reads properties from file Reads the current properties object from file. The 
    * file is stored in /home/mimibox/config/flag_config.properties 
    */ 

    public Properties readPropertiesFromFile() { 
     // create and load default properties 
     InputStream input = null; 
     logger.trace("Read flag config properties."); 
     try { 
      input = new FileInputStream(configFilename); 
      // load a properties file from class path, inside static method 
      props.load(input); 
      // get the property values and save 
      xPanelSizeStg = props.getProperty("xPanelsize", "32"); 
      yPanelSizeStg = props.getProperty("yPanelsize", "32"); 
     } catch (IOException ex) { 
      logger.error("Could not open config file" + configFilename, ex); 
     } finally { 
      if (input != null) { 
       try { 
        input.close(); 
       } catch (IOException e) { 
        logger.error("Could not close config file" + configFilename, e); 
       } 
      } 
     } 
     return props; 
    } 

    /** 
    * Writes properties to file Writes the current properties object to file. The 
    * file is stored in /home/mimibox/config/flag_config.properties 
    */ 

    public void writePropertiesToFile() { 
     // saves the current properties to file. Overwrites the existing properties. 
     // Properties props = new Properties(); // a list of properties 
     OutputStream outStrm = null; 
     logger.info("Writing default flag config properties."); 
     logger.debug("Panel size x = " + xPanelSizeStg); 
     try { 
      outStrm = new FileOutputStream(configFilename); 
      // set the properties values 
      //props.setProperty("xPanelsize", xPanelSizeStg); 
      //props.setProperty("yPanelsize", yPanelSizeStg); 
      // save properties to file, include a header comment 
      props.store(outStrm, "This is the Server configuration file"); 

     } catch (IOException io) { 
      logger.error("The file :{0} could not be opened", configFilename, io); 
     } finally { 
      if (outStrm != null) { 
       try { 
        outStrm.close(); 
       } catch (IOException e) { 
        logger.error("The file :{0} could not be closed", configFilename, e); 
       } 
      } 
     } 
    } 

    private void setProperty(String key, String value) { 
     this.props.setProperty(key, value); 
    } 

    public int getxPanelSize() { 
     return this.xPanelSize; 
    } 

    public void setxPanelSize(int xPanelSize) { 
     this.xPanelSize = xPanelSize; 
    } 

    public int getyPanelSize() { 
     return yPanelSize; 
    } 

    public void setyPanelSize(int yPanelSize) { 
     this.yPanelSize = yPanelSize; 
    } 

    public static void main(String[] args) { 
     Properties props = null; 
     ClientProperties p = new ClientProperties(); 
     props = p.readPropertiesFromFile(); 
     String xPanelsize = props.getProperty("xPanelsize"); 
     System.out.println("Panel size x = " + xPanelsize); 
     p.setProperty("xPanelsize", "64"); // method not found error 

     p.writePropertiesToFile(); 

     props = p.readPropertiesFromFile(); 
     xPanelsize = props.getProperty("xPanelsize"); 
     System.out.println("So, now the Panel size x = " + xPanelsize); 
    } 

} 
1

OK :

여기

enter image description here

은 전체 소스입니다 코멘트와 대답은 bove, 나는 많은 변화를 만들었습니다. 이 게시물에서 우연히 발견되는 사람들을 위해이 답변에 작업 코드를 게시했습니다. 주요 변경 사항은 속성을 확장하는 것입니다. 이를 통해 Properties 메서드를 직접 사용할 수 있습니다.

package com.test; 

import java.util.Properties; 
import java.io.FileOutputStream; 
import java.io.FileInputStream; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.io.IOException; 
import org.apache.logging.log4j.LogManager; 
import org.apache.logging.log4j.Logger; 
import java.io.File; 

public class ClientProperties extends Properties { 

    //initiate logger 

    private final static Logger logger = LogManager.getLogger(); 

    private static String xPanelSizeStg = "32"; 
    private static String yPanelSizeStg = "32"; 
    private final configFilename = "/home/myname/myConfig.properties"; 

    public ClientProperties() { 

    } 


    public Properties readPropertiesFromFile(){ 
     // create and load default properties 
     InputStream input = null; 
     logger.trace("Read flag config properties."); 
     try { 
      input = new FileInputStream(configFilename); 
      //load a properties file from class path, inside static method  
      this.load(input); 
      //get the property values and save 
      xPanelSizeStg = this.getProperty("xPanelsize","32"); 
      yPanelSizeStg = this.getProperty("yPanelsize", "32"); 
     } 
     catch (IOException ex) { 
      logger.error("Could not open config file" + configFilename,ex); 
     } 
     finally{ 
      if(input!=null){ 
       try { 
        input.close(); 
       } 
       catch (IOException e) { 
       logger.error("Could not close config file" + configFilename,e); 
       } 
      } 
     } 
     return this; 
    } 

    public void writePropertiesToFile() { 
    //saves the current properties to file. Overwrites the existing properties. 
    //Properties props = new Properties(); //a list of properties 
    OutputStream outStrm = null; 
    logger.info("Writing default flag config properties."); 
       System.out.println("Panel size x = " + xPanelSizeStg); 
    try { 
     outStrm = new FileOutputStream(configFilename); 
     // save properties to file, include a header comment 
     this.store(outStrm, "This is the Server configuration file"); 

     } catch (IOException io) { 
      logger.error("The file :{0} could not be opened", configFilename,io); 
     } finally { 
      if (outStrm!= null) { 
       try { 
        outStrm.close(); 
       } catch (IOException e) { 
        logger.error("The file :{0} could not be closed", configFilename, e); 
       } 
      } 
     } 
    } 
} 

나는 "this"로 액세스 한 등록 정보를 시작하기 위해 Properties 부모에게 의존했습니다. 이제 기본 모양은 다음과 같습니다.

public static void main(String[] args) { 

    ClientProperties p = new ClientProperties(); 
    p.readPropertiesFromFile(); 
    String txt = p.getProperty("xPanelsize"); 
     System.out.println("Panel size x = " + txt); 
    p.setProperty("xPanelsize","64"); 
    p.writePropertiesToFile(); 


} 

클래스는 이제 읽기, 쓰기 및 파일에 대한 모든 관리자를 숨 깁니다. 결정적으로 각 속성에 대한 setter/getter 작성을 피할 수 있습니다. 여기에 표시된 두 가지 속성보다 훨씬 많은 속성이 있습니다. 그것이 제가 첫 번째 판에서 가지고있는 것입니다.

도움 주셔서 감사합니다. 이 모든 것을 혼자서 알아내는 데는 오랜 시간이 걸렸을 것입니다.

관련 문제