- How to read/write data from/to .properties file in Java?
- Example
- Output
- Storing properties file in XML format
- Example
- Output
- How to create and store property file dynamically in Java?
- Creating a .properties file
- Example
- Output
- Storing properties file in XML format
- Example
- Output
- How to Create and Modify Properties File Form Java Program in Text and XML Format — Example
- Java program to create and store Properties in text and XML format
- Create or Write or dump java properties to file in java (example)
- 2. Program – write or create property file in java (example)
- 3. Property file in generated in work-space directory
- 4. Output – write or create property file in java (example)
- Простой пример работы с Property файлами в Java
- Шаг 0. Создание проекта
- Шаг 2. Добавляем конфигурационные данные в проперти файл
- Шаг 3. Получаем Property данные
How to read/write data from/to .properties file in Java?
The .properties is an extension in java which is used to store configurable application. It is represented by the Properties class in Java, you can store a properties file and read from it using the methods of this class. This class inherits the HashTable class.
Creating a .properties file −
To create a properties file −
- Instantiate the Properties class.
- Populate the created Properties object using the put() method.
- Instantiate the FileOutputStream class by passing the path to store the file, as a parameter.
Example
The Following Java program creates a properties file in the path D:/ExampleDirectory/
import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class CreatingPropertiesFile < public static void main(String args[]) throws IOException < //Instantiating the properties file Properties props = new Properties(); //Populating the properties file props.put("Device_name", "OnePlus7"); props.put("Android_version", "9"); props.put("Model", "GM1901"); props.put("CPU", "Snapdragon855"); //Instantiating the FileInputStream for output file String path = "D:\ExampleDirectory\myFile.properties"; FileOutputStream outputStrem = new FileOutputStream(path); //Storing the properties file props.store(outputStrem, "This is a sample properties file"); System.out.println("Properties file created. "); >>
Output
If you observe the output file you can see the created contents as −
Storing properties file in XML format
You can store the properties file in XML format using the stored XML() method.
Example
import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class CreatingPropertiesFile < public static void main(String args[]) throws IOException < //Instantiating the properties file Properties props = new Properties(); //Populating the properties file props.put("Device_name", "OnePlus7"); props.put("Android_version", "9"); props.put("Model", "GM1901"); props.put("CPU", "Snapdragon855"); //Instantiating the FileInputStream for output file String outputPath = "D:\ExampleDirectory\myFile.xml"; FileOutputStream outputStrem = new FileOutputStream(outputPath); //Storing the properties file in XML format props.storeToXML(outputStrem, "This is a sample properties file"); System.out.println("Properties file created. "); >>
Output
How to create and store property file dynamically in Java?
The .propertiesis an extension in java which is used to store configurable application. It is represented by the Properties class in Java, you can store a properties file and read from it using the methods of this class. This class inherits the HashTable class.
Creating a .properties file
To create a properties file −
- Instantiate the Properties class.
- Populate the created Properties object using the put() method.
- Instantiate the FileOutputStream class by passing the path to store the file, as a parameter.
Example
The Following Java program creates a properties file in the path D:/ExampleDirectory/
import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class CreatingPropertiesFile < public static void main(String args[]) throws IOException < //Instantiating the properties file Properties props = new Properties(); //Populating the properties file props.put("Device_name", "OnePlus7"); props.put("Android_version", "9"); props.put("Model", "GM1901"); props.put("CPU", "Snapdragon855"); //Instantiating the FileInputStream for output file String path = "D:\ExampleDirectory\myFile.properties"; FileOutputStream outputStrem = new FileOutputStream(path); //Storing the properties file props.store(outputStrem, "This is a sample properties file"); System.out.println("Properties file created. "); >>
Output
If you observe the output file you can see the created contents as −
Storing properties file in XML format
You can store the properties file in XMLformat using the storeToXML() method.
Example
import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class CreatingPropertiesFile < public static void main(String args[]) throws IOException < //Instantiating the properties file Properties props = new Properties(); //Populating the properties file props.put("Device_name", "OnePlus7"); props.put("Android_version", "9"); props.put("Model", "GM1901"); props.put("CPU", "Snapdragon855"); //Instantiating the FileInputStream for output file String outputPath = "D:\ExampleDirectory\myFile.xml"; FileOutputStream outputStrem = new FileOutputStream(outputPath); //Storing the properties file in XML format props.storeToXML(outputStrem, "This is a sample properties file"); System.out.println("Properties file created. "); >>
Output
If you observe the output file you can see the created contents as −
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
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» ) ;
Create or Write or dump java properties to file in java (example)
2. Program – write or create property file in java (example)
package org.learn; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class PropertyWriter < public static void main(String[] args) < writeProperties(); >private static void writeProperties() < FileOutputStream fileOutputStream = null; String fileName = "output.properties"; try < Properties properties = new Properties(); properties.setProperty("user.name", "admin"); properties.setProperty("user.age", "25"); properties.setProperty("user.country", "USA"); properties.setProperty("user.email", "[email protected]"); System.out.println("1. Start writing properties to Property file"); File writeFile = new File("output.properties"); fileOutputStream = new FileOutputStream(writeFile); properties.store(fileOutputStream, "Creating new property file"); System.out.println("2. Writing properties to Property file : " + properties.toString()); System.out.printf("3. Successfully written properties to file = %s", fileName); > catch (IOException e) < e.printStackTrace(); >finally < if (fileOutputStream != null) < try < fileOutputStream.close(); >catch (IOException e) < e.printStackTrace(); >> > > >
3. Property file in generated in work-space directory
Fig 2: Written property file in java4
4. Output – write or create property file in java (example)
1. Start writing properties to Property file 2. Writing properties to Property file : [email protected]> 3. Successfully written properties to file = output.properties
Простой пример работы с Property файлами в Java
Property файлы присутствуют практически в каждом проекте, и сейчас я вам покажу простой пример их использования, а также расскажу, зачем они и где используются.
Шаг 0. Создание проекта
Начнем с того что создадим простой Maven проект, указав название и имя пакета:
Структура, которая получится в конце проекта довольно таки простая.
Как видите у нас только два файла, первый – Main.java, а второй – config.properties.
Шаг 2. Добавляем конфигурационные данные в проперти файл
Проперти файлы либо файлы свойств – предназначены, для того чтобы хранить в них какие-то статические данные необходимые проект, например логин и пароль к БД.
Давайте добавим в наш config.properties логин и пароль (это любые данные, для того чтобы продемонстрировать работу с property файлами).
Содержимое config.properties:
db.host = http://localhost:8888/mydb db.login = root db.password = dbroot
ключ> – это уникальное имя, по которому можно получить доступ к значению, хранимому под этим ключом.
значение> – это текст, либо число, которое вам необходимо для выполнения определённой логики в вашей программе.
Шаг 3. Получаем Property данные
Как можно видеть в структуре проекта выше, там есть класс Main.java давайте его создадим и напишем в нем следующее:
package com.devcolibir.prop; import java.io.*; import java.util.Properties; public class Main < public static void main(String[] args) < FileInputStream fis; Properties property = new Properties(); try < fis = new FileInputStream("src/main/resources/config.properties"); property.load(fis); String host = property.getProperty("db.host"); String login = property.getProperty("db.login"); String password = property.getProperty("db.password"); System.out.println("HOST: " + host + ", LOGIN: " + login + ", PASSWORD: " + password); >catch (IOException e) < System.err.println("ОШИБКА: Файл свойств отсуствует!"); >> >
Обращаясь к property.getProperty(ключ>) – вы получаете его значение.
Вот такой краткий, но думаю познавательный урок.