Java properties изменить файл

Java Properties file

Здравствуйте Уважаемые. Подскажите, пожалуйста, как в Properties file изменить значение по ключу. У меня при изменении одного ключа, меняется весь файл, и остается единственная запись(через setProperty). Заранее спасибо.

Есть такое? XML + java.util.Properties
Нужен какой метод чтобы класс Пропертиес записать в хмл формате. задача проста конечно, просто.

Groovy Как использовать значения из *.properties файлов без Java кода (в compile time)
Привет! Видел в других проектах подобное использование #файл my.properties user.name =.

Java runnable jar сохранение в properties
Здраствуйте в проекте использую resource директорию, где находится текстовый файл. project/ src/.

butulec, Здравсвуйте уважаемый. Вы ождаете что вам ответят не видя вашего кода?
ps. работающих примеров с классом Properties полным полно гуглиться на русском

FileOutputStream out = new FileOutputStream("First.properties"); FileInputStream in = new FileInputStream("First.properties"); Properties props = new Properties(); props.load(in); in.close(); props.setProperty("country", "america"); props.store(out, null); out.close();

setProperty работает таким образом, что оставляет одну запись в файле «country=america»(при этом удаляет все остальные), а я хотел бы оставить все записи которые были в файле, изменив при этом только одну строчку.

Читайте также:  Php xml to json converter

Лучший ответ

Сообщение было отмечено butulec как решение

Решение

butulec, попробуйте так

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
public static void main(String[] args) { File file = new File("first.properties"); InputStream in = null; OutputStream out = null; Properties props = new Properties(); try { in = new FileInputStream(file); props.load(in); props.setProperty("country", "america"); out = new FileOutputStream(file); props.store(out, null); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }

Да все верно, мне уже подсказали )
Всё дело в том, что открытие файла через FileOutputStream стирает его содержимое. Правильный путь — открыть файл для чтения, считать параметры, закрыть, изменить параметры, открыть файл для записи и записать параметры. Приведённый ниже код решает Вашу задачу:

FileInputStream in = new FileInputStream("First.properties"); Properties props = new Properties(); props.load(in); in.close(); props.setProperty("country", "america"); FileOutputStream out = new FileOutputStream("First.properties"); props.store(out, null); out.close();

Источник

How to Create and Modify Properties File Form Java Program in Text and XML Format — Example

Though most of the time we create and modify properties file using text editors like notepad, word-pad or edit-plus, It’s also possible to create and edit properties file from Java program. Log4j.properties , which is used to configure Log4J based logging in Java and jdbc.properties which is used to specify configuration parameters for database connectivity using JDBC are two most common example of property file in Java. Though I have not found any real situation where I need to create properties file using Java program but it’s always good to know about facilities available in Java API.

In last Java tutorial on Properties we have seen how to read values from properties file on both text and XML format and in this article we will see how to create properties file on both text and XML format.

Java API’s java.util.Properties class provides several utility store() methods to store properties in either text or xml format. Store() can be used to store property in text properties file and storeToXML() method can be used for creating a Java property file in XML format.

Java program to create and store Properties in text and XML format

How to create Property file from Java program text and XML format

As I said earlier java.util.Properties represent property file in Java program. It provides load() and store() method to read and write properties files from and to the File system. Here is a simple example of creating Java property file form program itself.

import java.io.FileNotFoundException ;
import java.io.FileOutputStream ;
import java.io.IOException ;
import java.util.Properties ;

/**
* Java program to create and modify property file in text format and storing

*
* @author Javin Paul
*/
public class TextPropertyWriter

public static void main ( String args []) throws FileNotFoundException, IOException

//Creating properties files from Java program
Properties props = new Properties () ;
FileOutputStream fos = new FileOutputStream ( «c:/user.properties» ) ;

props. setProperty ( «key1» , «value1» ) ;
props. setProperty ( «key2» , «value2» ) ;

//writing properites into properties file from Java
props. store ( fos, «Properties file generated from Java program» ) ;

Источник

Java Properties Files: How to Update config.properties File in Java?

Java Properties Files - How to Update config.properties File in Java?

Properties files are a popular mean of configuring applications. Of course Commons Configuration supports this format and enhances significantly the basic java.util.Properties class.

This section introduces the features of the PropertiesConfiguration class. Note that Properties Configuration is a very typical example for an implementation of the Configuration interface and many of the features described in this section (e.g. list handling or interpolation) are supported by other configuration classes as well.

This is because most configuration implementations that ship with Commons Configuration are derived from the common base class AbstractConfiguration , which implements these features.

Below is a simple code which will help you update config.properties file via java. For reading properties file follow this tutorial.

You need this .jar files in your class path: commons-configuration-1.9.jar .

If you have maven project then use below dependency:

 commons-configuration commons-configuration 1.10  

CrunchifyUpdateConfig.java

Here is a simple program to update config.properties file.

package crunchify.com.tutorials; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; /** * @author Crunchify.com * Java Properties Files: How to Update config.properties File in Java? */ public class CrunchifyUpdateConfig < public static void main(String[] args) throws ConfigurationException < // You have to create config.properties file under resources folder or anywhere you want :) // Here I'm updating file which is already exist under /Documents // PropertiesConfiguration: This is the "classic" Properties loader which loads the values from a single or multiple files (which can be chained with "include =". // All given path references are either absolute or relative to the file name supplied in the constructor. // In this class, empty PropertyConfigurations can be built, properties added and later saved. // Include statements are (obviously) not supported if you don't construct a PropertyConfiguration from a file. // The properties file syntax is explained here, // basically it follows the syntax of the stream parsed by java.util.Properties.load and adds several useful extensions PropertiesConfiguration config = new PropertiesConfiguration("/Users/app/Documents/config.properties"); // setProperty(): Sets a new value for the specified property. // This implementation checks if the auto save mode is enabled and saves the configuration if necessary. config.setProperty("company1", "Crunchify"); config.setProperty("company2", "Google"); config.setProperty("Crunchify_Address", "NYC, US"); config.setProperty("Google_Address", "Mountain View, CA, US"); // save(): Save the configuration. Before this method can be called a valid file name must have been set. config.save(); System.out.println("Config Property Successfully Updated.."); >>

Console Result:

Just run above program as a Java Application and you should see result as below.

log4j:WARN No appenders could be found for logger (org.apache.commons.configuration.PropertiesConfiguration). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. Config Property Successfully Updated..

config.properties file content:

Just to to Downloads folder and you should see file with below contents.

Config.properties file via Java

Let us know if you face any issue running above program.

If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion.

Suggested Articles.

Источник

Update Property Values During Runtime in Java

We provide constant values required through property files. Properties are static key value pairs read during start of project.

In a case if I want to use a value from current execution in next run?.

I can achieve this by storing value in a test results file and read it back in next run. Another way is to store a value in my property file with key “LastFailedcount” and value from current execution.

Storing key value pair is easier for me as I don’t need to look for last results file every time. And property file initiation is one time activity for each execution.

Reading Properties file

package automation; import java.io.InputStream; import java.util.Properties; public class rwProperties < //Initiating Java Properties class object public static Properties prop = new Properties(); public void readProperties() < try < //Reading the fiel as Inputstream from Project Resources path // File located in Properties folder under Project Resources InputStream input = Main.class.getResourceAsStream("/properties/prop.xml"); // This would load the inputstream to properties class of java prop.loadFromXML(input); //Close the inputstream to reduce resource leak input.close(); >catch (IOException | NullPointerException e) < System.out.print(e) >> >

now you will use the desired key value by

Let us see how can we update property values during runtime. I took example of Properties file in XML format in this tutorial.

For an instance I got my Property file with Key “LastFailedCount”, which records failed testcase count from last execution.

I want this count to be used to compare and provide failure percentage metrics for last vs current execution.

Once I generate metric I want to replace the failure count from current execution. So next time this value can be used.

First create a object for Java Properties class, below creates a object that has no default values.

Properties newPropValue = new Properties();

Now load already read properties to this object.

Then update the desired key value as required

newPropValue.setProperty("LastFailedCount", newValue); //here newValue would be the Failed count you recorded as par tof your current run.

You need to then read the file to which you want to update. If you want to use same way how you read the file in readProperties(); then it would not work out while saving the file back.

For this you need to get the absolute path for the file.

//System.getProperty("user.dir") will return the eaxct location of project directory on the system File file = new File(System.getProperty("user.dir") + "/src/test/resources/properties/prop.xml");

Then you need to load the file to output stream using FileOutputStream class of java.io

FileOutputStream out = new FileOutputStream(file);

Then write / store the value to the file.

// Syntax for storing is (File, Comment for the update) //Comment is optional //Here I am using local time when it updated. newPropValue.storeToXML(out, "Count Updated at "+ LocalDate.now());

Finally close the output stream, this would help to reduce resource leak.

public void writetoProp(String key, String propValue) < Properties newPropValue= new Properties(); newPropValue.putAll(prop); newPropValue.setProperty(key, propValue); FileOutputStream out; try < file = new File(System.getProperty("user.dir") + "/src/test/resources/properties/prop.xml"); out = new FileOutputStream(file); newPropValue.storeToXML(out, "ID Updated on "+ LocalDate.now()); out.close(); >catch (IOException e) < Sytem.out.print(e) >>

This is how you can update property value during runtime.

Let us look at whole class with read and write to property file.

package automation; import java.io.InputStream; import java.util.Properties; import java.io.IOException; import java.io.FileOutputStream; import java.time.LocalDate; public class rwProperties < //Initiating Java Properties class object public static Properties prop = new Properties(); public void readProperties() < try < //Reading the fiel as Inputstream from Project Resources path // File located in Properties folder under Project Resources InputStream input = Main.class.getResourceAsStream("/properties/prop.xml"); // This would load the inputstream to properties class of java prop.loadFromXML(input); //Close the inputstream to reduce resource leak input.close(); >catch (IOException | NullPointerException e) < System.out.print(e) >> public void writetoProp(String key, String newValue) < Properties newPropValue= new Properties(); newPropValue.putAll(prop); newPropValue.setProperty(key, newValue); FileOutputStream out; try < file = new File(System.getProperty("user.dir") + "/src/test/resources/properties/prop.xml"); out = new FileOutputStream(file); newPropValue.storeToXML(out, "ID Updated on "+ LocalDate.now()); out.close(); >catch (IOException e) < Sytem.out.print(e) >>

You need to call this updating method finally when your site execution finish.

@AfterSuite public void updaetFailedCount() < //Failed count is the variable which stores value to be updated writetoProp("LastFailedCount", failedCount) >

Источник

Русские Блоги

Класс Java Properties для чтения и изменения информации о файле конфигурации

Когда мы обычно пишем программы, некоторые параметры часто меняются, и это изменение не предвидится. Например, мы разработали модуль, который управляет базой данных, во время разработки мы подключаемся к локальной базе данных. IP Имя базы данных, имя таблицы, хост базы данных и другая информация являются локальными для нас, чтобы сделать этот модуль рабочих данных универсальным, тогда вышеупомянутая информация не может быть записана в программе. Обычно наш подход заключается в использовании файлов конфигурации для решения. Каждый язык имеет свои поддерживаемые типы файлов конфигурации. такие как Python Он поддерживает .ini файл. Потому что у него есть nfigParser Класс для поддержки .ini Чтение и запись файлов, программисты могут свободно работать в соответствии с методами, предоставляемыми этим классом .ini файл. Пока в Java в, Java Поддержка .properties Чтение и запись файлов. JDK Встроенный java.util.Properties У нас работают классы .properties Файл обеспечивает удобство.

Ниже приведена информация о сервере и базе данных.

# Ниже приведена информация таблицы базы данных

# Ниже приведена информация о сервере

В приведенном выше файле мы предполагаем, что имя файла: test.properties файл. из их # Первая строка комментария информации; в знаке равенства » = «Тот, что слева называется key ;знак равенства» = «Правый называется value , (На самом деле ключ мы часто говорим — Значение пары) key Это должна быть переменная в нашей программе. а также value Мы настроены в соответствии с реальной ситуацией.

Ниже приведены классы инструментов для работы с файлами свойств:

import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; /** * Java чтение и запись для изменения файла свойств * @author xiewanzhi * @date 2011-4-7 09:19:03 утра * @version 1.0 */ public class PropertiesConfig < /** * Согласно КЛЮЧУ, прочитайте соответствующее значение файла * @param filePath - путь к файлу, то есть путь к пакету, в котором находится файл, например: java / util / config.properties * ключ @param * Значение, соответствующее ключу @return */ public static String readData(String filePath, String key) < // Получить абсолютный путь filePath = PropertiesConfig.class.getResource("/" + filePath).toString(); // Префикс "file:" усеченного пути filePath = filePath.substring(6); Properties props = new Properties(); try < InputStream in = new BufferedInputStream(new FileInputStream(filePath)); props.load(in); in.close(); String value = props.getProperty(key); return value; >catch (Exception e) < e.printStackTrace(); return null; >> /** * Изменить или добавить пары ключ-значение. Если ключ существует, измените его, в противном случае добавьте его. * @param filePath - путь к файлу, то есть путь к пакету, в котором находится файл, например: java / util / config.properties * ключ @param * Значение, соответствующее ключу значения @param */ public static void writeData(String filePath, String key, String value) < // Получить абсолютный путь filePath = PropertiesConfig.class.getResource("/" + filePath).toString(); // Префикс "file: /" усеченного пути filePath = filePath.substring(6); Properties prop = new Properties(); try < File file = new File(filePath); if (!file.exists()) file.createNewFile(); InputStream fis = new FileInputStream(file); prop.load(fis); // Обязательно закройте fis перед изменением значения fis.close(); OutputStream fos = new FileOutputStream(filePath); prop.setProperty(key, value); // Сохраняем и добавляем комментарии prop.store(fos, "Update '" + key + "' value"); fos.close(); >catch (IOException e) < System.err.println("Visit " + filePath + " for updating " + value + " value error"); >> public static void main(String[] args) < System.out.println(PropertiesConfig.readData("com/xiewanzhi/property/config.properties", "port")); // PropertiesConfig.writeData("com/xiewanzhi/property/config.properties", "port", "12345"); >>

Источник

Оцените статью