如何通过java代码在属性文件中写入值

use*_*418 21 java

我有一个问题.

我有一个属性文件.我想在该文件中存储一些值,并在需要时在代码中实现.有没有办法做到这一点?

我正在Properties上课这样做..

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)


Dev*_*ata 5

您可以通过以下方式执行此操作:

  1. Properties使用,首先在对象中设置属性object.setProperty(String obj1, String obj2).

  2. 然后把它写入你File通过传递FileOutputStreamproperties_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)