2017-09-24 4 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()メソッドを使用できます。私がそれをすると、変更されたプロパティはファイルに書き込まれません。 1つ以上のPropertyインスタンスがあり、1つはPropertyインスタンスには見えないためです。私は、私がやりたいことを達成するために組み込みのPropertiesクラスを拡張する必要があると思うが、それをすべて動作させる方法がわからない。

インターネットでプロパティを使用する例はたくさんあります。私が見つけていないのは、クラス内の関連するファイルI/Oを隠す例です。それはどうすればいいのですか?

+0

1. Yoyはp.setProperty()の代わりにprops.setProperty()を呼び出す必要があります。 2. Uは、writePropertiesToFile()メソッドの同じキー "xPanelsize"を古い値でオーバーライドしているため、反映されません。 –

+0

あなたは 'java.util.ResourceBundle'を知っていますか? – EJP

+0

漠然としかありません。それを使用することを検討するのに十分ではありません。 – dazz

答えて

0

「props」オブジェクト用のゲッターを作成する必要があります。

public Properties getProps() 
{ 
    return props; 
} 

そして、あなたはこのようにそれを呼び出すことができるようになります:あなたは、プロパティクラスの子供たちは、その後、あなたが使用する必要がありますあなたのClientPropertiesクラスを作ることを計画している場合は、

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

をOR「拡張

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

この場合、クラスのフィールドには任意のプロパティオブジェクトは必要ありません。

+0

私の非常に限られた知識に基づいて、プロパティを拡張するのが最善の選択肢のように聞こえます。私は変更を行う際に行きます。 – dazz

+0

これは私が作業コードを書くために必要な情報を与えたので、これを答えとしてチェックしました。他の人の利益のために私の答えに作業コードが提供されています。 – dazz

0

これは私の提案です。あなただけのクラスのグローバル変数-props-を使用してsetPropertyメソッドを作成し、その後

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); 
      } 
     } 
    } 
} 

まず、あなたが再びこのようなあなたのwritePropertiesToFile方法でプロパティを編集する必要はありません。 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

次のとおりです。ここで

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ように感謝コメントと回答は私はいくつかの変更を加えました。この記事につきまとう人のために、私はこの答えに作業コードを掲載しました。主な変更は、プロパティを拡張することです。これにより、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); 
       } 
      } 
     } 
    } 
} 

私は「これ」でアクセスしたプロパティを開始するためにプロパティの親に頼っています。だから、今のメインは次のようになります:

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を書くことを避けることです(ここに示す2つのプロパティよりも多くのプロパティがあります)。それは私が最初のバージョンで持っていたものです。

ありがとうございました。それは私自身でこれをすべて理解するのに長い時間がかかりました。

関連する問題