我有一个问题。
我有一个属性文件。我想在该文件中存储一些值,并在需要时在代码中实现。有没有办法做到这一点?
我正在使用Properties
类来做这件事..
答案 0 :(得分:25)
使用java.util.Properties
加载属性文件。
代码段 -
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("xyz.properties");
prop.load(in);
它提供Properties#setProperty(java.lang.String, java.lang.String)
,有助于添加新属性。
代码段 -
prop.setProperty("newkey", "newvalue");
您可以使用Properties#store(java.io.OutputStream, java.lang.String)
代码段 -
prop.store(new FileOutputStream("xyz.properties"), null);
答案 1 :(得分:5)
您可以通过以下方式执行此操作:
使用Properties
在object.setProperty(String obj1, String obj2)
对象中首先设置属性。
然后将File
传递给FileOutputStream
,将其写入properties_object.store(FileOutputStream, String)
。
以下是示例代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.File;
class Main
{
static File file;
static void saveProperties(Properties p) throws IOException
{
FileOutputStream fr = new FileOutputStream(file);
p.store(fr, "Properties");
fr.close();
System.out.println("After saving properties: " + p);
}
static void loadProperties(Properties p)throws IOException
{
FileInputStream fi=new FileInputStream(file);
p.load(fi);
fi.close();
System.out.println("After Loading properties: " + p);
}
public static void main(String... args)throws IOException
{
file = new File("property.dat");
Properties table = new Properties();
table.setProperty("Shivam","Bane");
table.setProperty("CS","Maverick");
System.out.println("Properties has been set in HashTable: " + table);
// saving the properties in file
saveProperties(table);
// changing the property
table.setProperty("Shivam", "Swagger");
System.out.println("After the change in HashTable: " + table);
// saving the properties in file
saveProperties(table);
// loading the saved properties
loadProperties(table);
}
}
答案 2 :(得分:1)
您的问题尚不清楚,因为从属性文件写入/读取已经在Java中提供。
要写入属性文件,可以使用您提到的Properties类:
Properties properties = new Properties();
try(OutputStream outputStream = new FileOutputStream(PROPERTIES_FILE_PATH)){
properties.setProperty("prop1", "Value1");
properties.setProperty("prop2", "Value2");
properties.store(outputStream, null);
} catch (IOException e) {
e.printStackTrace();
}
答案 3 :(得分:0)
这对我有用。
Properties prop = new Properties();
try {
InputStream in = new FileInputStream("src/loop.properties");
prop.load(in);
} catch (IOException ex) {
System.out.println(ex);
}
//Setting the value to our properties file.
prop.setProperty("LOOP", "1");
//Getting the value from our properties file.
String value = prop.getProperty("LOOP").trim();
try {
prop.store(new FileOutputStream("src/loop.properties"), null);
} catch (IOException ex) {
System.out.println(ex);
}