Java 设置属性并将其存储在文件中
我有一个类,它处理来自包的给定“配置文件”。因为我只需要处理简单的键/值对,所以我认为使用Java 设置属性并将其存储在文件中,java,oop,file-io,Java,Oop,File Io,我有一个类,它处理来自包的给定“配置文件”。因为我只需要处理简单的键/值对,所以我认为使用Properties就可以了 import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class ConfigFile { private Properties appProps = new P
Properties
就可以了
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ConfigFile {
private Properties appProps = new Properties();
private String filename;
private InputStream in;
public ConfigFile(String file) throws FileNotFoundException, IOException {
this.filename = file;
in = getClass().getResourceAsStream(this.filename);
appProps.load(in);
in.close();
}
public String getProp(String key) {
return appProps.getProperty(key);
}
}
现在,我想创建一个setProp(String key,String value)
方法,显然,它设置给定的属性,并将其保存到从中读取的同一个文件中。我只是不知道怎么做。我想我需要调用appProps.setProperty(key,value)
,然后使用OutputStream
执行某种魔术,但我一直坚持这样做。任何帮助都将不胜感激
Properties prop = new Properties();
try (FileOutputStream os = new FileOutputStream("config.properties"))
{
//set the properties value
prop.setProperty("database", "localhost");
prop.setProperty("dbuser", "mkyong");
prop.setProperty("dbpassword", "password");
//save properties to project root folder
prop.store(os, null);
} catch (IOException ex) {
ex.printStackTrace();
}
这应该解释一切,如果你不想问的话
这应该可以解释一切,如果你不想问的话。自动保存的功能不在
属性类中直接提供,但是你可以组合现有的功能。您必须自己实现这个组合,或者通过子类化属性
并实现一个新方法,或者通过添加一个实用方法。如果您对现有属性不感兴趣,可以编写如下代码:
void update(String file, String key, String value) throws IOException {
Properties properties = new Properties();
InputStream is = new FileInputStream(new File(file));
try {
properties.load(is);
} finally {
is.close();
}
properties.setProperty(key, value);
OutputStream os = new FileOutputStream(new File(file));
try {
properties.store(os);
} finally {
os.close();
}
}
自动保存的此类功能不直接在属性
类中提供,但您可以组合现有功能。您必须自己实现这个组合,或者通过子类化属性
并实现一个新方法,或者通过添加一个实用方法。如果您对现有属性不感兴趣,可以编写如下代码:
void update(String file, String key, String value) throws IOException {
Properties properties = new Properties();
InputStream is = new FileInputStream(new File(file));
try {
properties.load(is);
} finally {
is.close();
}
properties.setProperty(key, value);
OutputStream os = new FileOutputStream(new File(file));
try {
properties.store(os);
} finally {
os.close();
}
}
您希望何时更新属性文件?每次更新appProps
时,或者当应用程序关闭时,或者在某个其他更新间隔时?我认为每次更新appProps
。这可能不是最节省资源的方法,但无论如何也不会被使用太多次。您希望何时更新属性文件?每次更新appProps
时,或者当应用程序关闭时,或者在某个其他更新间隔时?我认为每次更新appProps
。这可能不是最有效的资源方式,但无论如何不会被太多的使用。不要使用FileOutputStream
这样。它会泄露的,好吧,你说得对,我会编辑它。只是检查了代码,实际上,流只是被刷新,但没有关闭。谢谢你的提示!不要像那样使用FileOutputStream
。它会泄露的,好吧,你说得对,我会编辑它。只是检查了代码,实际上,流只是被刷新,但没有关闭。谢谢你的提示!