创建一个类来包装属性
我想创建一个包装属性并专门隐藏文件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实例,另一个对另一个不可见。我想我需要扩展内置的Properties类来实现我想要做的事,但我不知道如何使它全部工作。
我发现了很多在互联网上使用属性的例子。我还没有找到任何隐藏类中的相关文件I/O的例子。我会怎么做?
您应该可能需要为您的'道具'物件创建一个吸气剂。
public Properties getProps()
{
return props;
}
而你,也就能够调用它像这样:
p.getProps().setProperty("key", "value");
或者,如果您打算让您的ClientProperties类属性类的孩子,那么你就需要使用“延伸',你将能够使用
p.setProperty("key", "value");
在这种情况下,你就不需要在类中的任何属性的对象调用它的领域。
这是我对你的例子的建议。
首先,你不必是编辑再次在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方法。
private void setProperty(String key, String value) {
this.props.setProperty(key, value);
}
如果你的属性文件看起来像下面的图片:
xPanelsize的值应该运行的应用程序后更改。
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);
}
属性文件内容将是:
这里充满来源:
package *;
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);
}
}
行,所以拜评论和答案a博夫,我做了一些改变。对于那些偶然发现这篇文章的人,我已经在这个答案中发布了工作代码。主要的变化是扩展属性。这使我可以直接使用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”访问过的属性。所以现在主要的样子:
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(并且我拥有比这里显示的两个更多的属性)。这是我的第一个版本。
感谢您的帮助。如果我自己弄清楚这一切,我将花费很长时间。
1. Yoy应该调用props.setProperty()而不是p.setProperty()。 2.用旧值重写方法writePropertiesToFile()中的同一个关键字“xPanelsize”,所以它没有被反映出来。 –
您是否知道'java.util.ResourceBundle'? – EJP
只有模糊。不够好考虑使用它。 – dazz