web-dev-qa-db-ja.com

ファイル全体を上書きせずに.propertiesの1つのプロパティを上書きする方法は?

基本的に、Java app)を使用して.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();
26
user890704

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

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

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


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

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

これはいくつかのユースケースで機能します。ただし、ロード/保存では、プロパティの順序を変更し、埋め込まれたコメントと空白を削除する必要があります。これらのことmay matter1

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


1-デザイナーが意図したとおりにAPIを使用する場合、プロパティの順序、埋め込まれたコメントなどwould n'tが重要です。しかし、OPが「実用的な理由」のためにこれを行っていると仮定しましょう。

20
Stephen C

Apache Commons Configuration から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();
14
davidpolo

別の答えは Apache Commons Configuration ライブラリ、特に機能 PropertiesConfigurationLayout を思い出させました。

これにより、元のレイアウト、コメント、順序などを(多かれ少なかれ)保存することができます。

3
Dave Newton

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

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

1
parsifal

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

  1. ファイルを読み取り、プロパティオブジェクトを読み込みます
  2. 「.setProperty」メソッドを使用して、新しいプロパティを更新または追加します。 (setPropertyメソッドは、プロパティオブジェクトの挿入と更新に使用できるため、.putメソッドよりも優れています)
  3. プロパティオブジェクトをファイルに書き戻し、ファイルを変更と同期させます。
1
Prateek Jain
import Java.io.*;
import Java.util.*;
class 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();
        }

    }
}
0
Yalamati
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", "[email protected]");
        props.setProperty("email.support_2", "[email protected]");

       // 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);
      }
   }
}

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

[email protected]
0
rIshab1988