Подтвердить что ты не робот

Как перезаписать одно свойство в .properties без перезаписи всего файла?

В принципе, я должен перезаписать определенное свойство в файле .properties через приложение Java, но когда я использую Properties.setProperty() и Properties.Store(), он перезаписывает весь файл, а не только одно свойство.

Я попытался построить FileOutputStream с append = true, но с этим он добавляет другое свойство и не удаляет/не перезаписывает существующее свойство.

Как я могу его закодировать так, чтобы установка одного свойства перезаписывала это конкретное свойство без перезаписи всего файла?

Изменить: я попытался прочитать файл и добавить его. Здесь мой обновленный код:

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();
4b9b3361

Ответ 1

API Properties не предоставляет никаких методов для добавления/замены/удаления свойства в файле свойств. Модель, поддерживаемая API, - загрузить все свойства из файла, внести изменения в объект Properties в памяти, а затем сохранить все свойства в файл (тот же или другой).

Но API Properties не является необычным в этом отношении. В действительности обновление на месте текстового файла сложно реализовать без перезаписи всего файла. Эта трудность является прямым следствием того, как файлы/файловые системы реализуются современной операционной системой.

Если вам действительно нужно делать инкрементные обновления, вам нужно использовать какую-то базу данных для хранения свойств, а не файл ".properties".

Ответ 2

Вы можете использовать PropertiesConfiguration из Конфигурация сообщества Apache.

В версии 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();

Ответ 3

Другой ответ напомнил мне о Apache Commons конфигурацию библиотеки, в частности, возможности PropertiesConfigurationLayout.

Это позволяет (более или менее) сохранить исходный макет, комментарии, порядок и т.д.

Ответ 4

Файлы свойств - это простой способ предоставить конфигурацию для приложения, но не обязательно хороший способ сделать программную, настраиваемую пользователем настройку только по той причине, что вы нашли.

Для этого я бы использовал API Настройки.

Ответ 5

Я делаю следующий метод: -

  • Прочитайте файл и загрузите объект свойств
  • Обновление или добавление новых свойств с помощью метода ".setProperty". (метод setProperty лучше, чем метод .put, поскольку он может использоваться для вставки, а также для обновления объекта свойства).
  • Введите объект свойства обратно в файл, чтобы файл синхронизировался с изменением.

Ответ 6

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

    }
}

Ответ 7

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]

Ответ 8

Да, это возможно. Если вы не хотите удалять свой контент из файла свойств. Просто прочитайте и замените строку из файла.

    String file="D:\\path of your file\abc.properties";     
    Path path = Paths.get(file);
    Charset charset = StandardCharsets.UTF_8;

    String content = new String(Files.readAllBytes(path), charset);
    content = content.replaceAll("name=anything", "name=anything1");
    Files.write(path, content.getBytes(charset));

Приведенный выше код не будет удалять содержимое из вашего файла. Он просто заменяет часть содержимого из файла.