28

基本的に、Java アプリを使用して .properties ファイル内の特定のプロパティを上書きする必要がありますが、Properties.setProperty() および Properties.Store() を使用すると、その 1 つのプロパティだけでなく、ファイル全体が上書きされます。

append = true で FileOutputStream を構築しようとしましたが、別のプロパティを追加し、既存のプロパティを削除/上書きしません。

ファイル全体を上書きせずに、1 つのプロパティを設定するとその特定のプロパティが上書きされるようにコーディングするにはどうすればよいですか?

編集:ファイルを読み取って追加しようとしました。更新されたコードは次のとおりです。

FileOutputStream out = new FileOutputStream("file.properties");
FileInputStream in = new FileInputStream("file.properties");
Properties props = new Properties();

props.load(in);
in.close();

props.setProperty("somekey", "somevalue");
props.store(out, null);
out.close();
4

8 に答える 8

21

API は、プロパティ ファイル内のプロパティを追加/置換/削除するためのPropertiesメソッドを提供しません。API がサポートするモデルは、ファイルからすべてのプロパティを読み込み、メモリ内Propertiesオブジェクトに変更を加えてから、すべてのプロパティをファイル (同じものまたは別のもの) に保存することです。

しかし、PropertiesAPI はその点で珍しいものではありません。実際には、テキスト ファイルのインプレース更新は、ファイル全体を書き換えずに実装することは困難です。この問題は、最新のオペレーティング システムによるファイル/ファイル システムの実装方法の直接的な結果です。

本当に増分更新を行う必要がある場合は、「.properties」ファイルではなく、ある種のデータベースを使用してプロパティを保持する必要があります。


その他の回答では、さまざまな形で次のアプローチが提案されています。

  1. Propertiesプロパティをファイルからオブジェクトに読み込みます。
  2. オブジェクトを更新しPropertiesます。
  3. Propertiesオブジェクトを既存のファイルの上に保存します。

これは、いくつかのユースケースで機能します。ただし、ロード/保存では、プロパティが並べ替えられたり、埋め込まれたコメントや空白が削除されたりする可能性があります。これらのことは重要かもしれませ1

もう1つのポイントは、これにはプロパティファイル全体の書き換えが含まれることです。これは、OPが明示的に回避しようとしています。


1 - API が設計者の意図どおりに使用されている場合、プロパティの順序、埋め込まれたコメントなどは問題になりません。ただし、OPが「実用的な理由」でこれを行っていると仮定しましょう。
2 -これを避けるのは現実的ではありません。前を参照してください。

于 2011-09-18T14:36:54.813 に答える
17

ApacheCommonsConfigurationからPropertiesConfigurationを使用できます。

バージョン1.Xの場合:

PropertiesConfiguration config = new PropertiesConfiguration("file.properties");
config.setProperty("somekey", "somevalue");
config.save();

バージョン2.0から:

Parameters params = new Parameters();
FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
    new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
    .configure(params.properties()
        .setFileName("file.properties"));
Configuration config = builder.getConfiguration();
config.setProperty("somekey", "somevalue");
builder.save();
于 2013-03-20T11:27:12.413 に答える
1

プロパティ ファイルは、アプリケーションの構成を提供する簡単な方法ですが、プログラムによるユーザー固有のカスタマイズを行うには必ずしも良い方法ではありません。

そのためには、Preferences API を使用します。

于 2011-09-18T14:43:45.420 に答える
1

私は次の方法を行います:-

  1. ファイルを読み取り、プロパティ オブジェクトをロードします。
  2. 「.setProperty」メソッドを使用して、新しいプロパティを更新または追加します。(setProperty メソッドは、プロパティ オブジェクトの挿入と更新に使用できるため、.put メソッドよりも優れています)
  3. プロパティ オブジェクトをファイルに書き戻して、ファイルを変更と同期させます。
于 2016-10-04T06:33:43.190 に答える
0
public class PropertiesXMLExample {
    public static void main(String[] args) throws IOException {

    // get properties object
    Properties props = new Properties();

    // get path of the file that you want
    String filepath = System.getProperty("user.home")
            + System.getProperty("file.separator") +"email-configuration.xml";

    // get file object
    File file = new File(filepath);

    // check whether the file exists
    if (file.exists()) {
        // get inpustream of the file
        InputStream is = new FileInputStream(filepath);

        // load the xml file into properties format
        props.loadFromXML(is);

        // store all the property keys in a set 
        Set<String> names = props.stringPropertyNames();

        // iterate over all the property names
        for (Iterator<String> i = names.iterator(); i.hasNext();) {
            // store each propertyname that you get
            String propname = i.next();

            // set all the properties (since these properties are not automatically stored when you update the file). All these properties will be rewritten. You also set some new value for the property names that you read
            props.setProperty(propname, props.getProperty(propname));
        }

        // add some new properties to the props object
        props.setProperty("email.support", "donot-spam-me@nospam.com");
        props.setProperty("email.support_2", "donot-spam-me@nospam.com");

       // get outputstream object to for storing the properties into the same xml file that you read
        OutputStream os = new FileOutputStream(
                System.getProperty("user.home")
                        + "/email-configuration.xml");

        // store the properties detail into a pre-defined XML file
        props.storeToXML(os, "Support Email", "UTF-8");

        // an earlier stored property
        String email = props.getProperty("email.support_1");

        System.out.println(email);
      }
   }
}

プログラムの出力は次のようになります。

support@stackoverflow.com
于 2013-06-25T02:49:57.223 に答える
-1

java.io.*をインポートします。

importjava.util。*;

クラスWritePropertiesFile

{{

         public static void main(String[] args) {
    try {
        Properties p = new Properties();
        p.setProperty("1", "one");
        p.setProperty("2", "two");
        p.setProperty("3", "three");

        File file = new File("task.properties");
        FileOutputStream fOut = new FileOutputStream(file);
        p.store(fOut, "Favorite Things");
        fOut.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

}

于 2013-03-14T21:38:47.600 に答える