Sub*_*der 26
使用加载属性文件java.util.Properties.
代码段 -
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("xyz.properties");
prop.load(in);
Run Code Online (Sandbox Code Playgroud)
它提供了Properties#setProperty(java.lang.String, java.lang.String)有助于添加新属性.
代码段 -
prop.setProperty("newkey", "newvalue");
Run Code Online (Sandbox Code Playgroud)
这个新设置可以保存使用 Properties#store(java.io.OutputStream, java.lang.String)
代码片段 -
prop.store(new FileOutputStream("xyz.properties"), null);
Run Code Online (Sandbox Code Playgroud)
您可以通过以下方式执行此操作:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
54595 次 |
| 最近记录: |