Java properties to inputstream

Java Read and Write Properties File Example

In this Java tutorial, learn to read properties file using Properties.load() method. Also we will use Properties.setProperty() method to write a new property into the .properties file.

Given below is a property file that we will use in our example.

firstName=Lokesh lastName=Gupta blog=howtodoinjava technology=java

2. Reading Properties File

In most applications, the properties file is loaded during the application startup and is cached for future references. Whenever we need to get a property value by its key, we will refer to the properties cache and get the value from it.

The properties cache is usually a singleton static instance so that application does not require to read the property file multiple times; because the IO cost of reading the file again is very high for any time-critical application.

Example 1: Reading a .properties file in Java

In the given example, we are reading the properties from a file app.properties which is in the classpath. The class PropertiesCache acts as a cache for loaded properties.

The file loads the properties lazily, but only once.

import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.Set; public class PropertiesCache < private final Properties configProp = new Properties(); private PropertiesCache() < //Private constructor to restrict new instances InputStream in = this.getClass().getClassLoader().getResourceAsStream("application.properties"); System.out.println("Reading all properties from the file"); try < configProp.load(in); >catch (IOException e) < e.printStackTrace(); >> //Bill Pugh Solution for singleton pattern private static class LazyHolder < private static final PropertiesCache INSTANCE = new PropertiesCache(); >public static PropertiesCache getInstance() < return LazyHolder.INSTANCE; >public String getProperty(String key) < return configProp.getProperty(key); >public Set getAllPropertyNames() < return configProp.stringPropertyNames(); >public boolean containsKey(String key) < return configProp.containsKey(key); >>

In the above code, we have used Bill Pugh technique for creating a singleton instance.

public static void main(String[] args) < //Get individual properties System.out.println(PropertiesCache.getInstance().getProperty("firstName")); System.out.println(PropertiesCache.getInstance().getProperty("lastName")); //All property names System.out.println(PropertiesCache.getInstance().getAllPropertyNames()); >
Read all properties from file Lokesh Gupta [lastName, technology, firstName, blog]

3. Writing into the Property File

Читайте также:  First person death для css

Personally, I do not find any good reason for modifying a property file from the application code. Only time, it may make sense if you are preparing data for exporting to third party vendor/ or application that needs data in this format only.

Example 2: Java program to write a new key-value pair in properties file

So, if you are facing similar situation then create two more methods in PropertiesCache.java like this:

public void setProperty(String key, String value) < configProp.setProperty(key, value); >public void flush() throws FileNotFoundException, IOException < try (final OutputStream outputstream = new FileOutputStream("application.properties");) < configProp.store(outputstream,"File Updated"); outputstream.close(); >>
  • Use the setProperty(k, v) method to write new property to the properties file.
  • Use the flush() method to write the updated properties back into the application.properties file.
PropertiesCache cache = PropertiesCache.getInstance(); if(cache.containsKey("country") == false) < cache.setProperty("country", "INDIA"); >//Verify property System.out.println(cache.getProperty("country")); //Write to the file PropertiesCache.getInstance().flush();
Reading all properties from the file INDIA

And the updated properties file is:

#File Updated #Fri Aug 14 16:14:33 IST 2020 firstName=Lokesh lastName=Gupta technology=java blog=howtodoinjava country=INDIA

That’s all for this simple and easy tutorial related to reading and writing property files using java.

Источник

How to read and write Properties file in java 8

In Java, properties files are used to store data and configuration. This tutorial will show you how to store and read properties files in Java 8.

Using InputStream and OutputStream

Write to properties file​

import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; public class PropertiesFileSample   final private static String PROPERTIES_FILE_PATH="config.properties";  public static void main(String[] args)   Properties properties = new Properties();  // using java 8 try-with-resources structure,  // so the output stream will be closed automatically  try(OutputStream outputStream = new FileOutputStream(PROPERTIES_FILE_PATH))   // set some values  properties.setProperty("username", "sampleusername");  properties.setProperty("url", "tutoref.com");  // store the values  properties.store(outputStream, null);  > catch (IOException e)  e.printStackTrace();  >  > > 

The result will look like this :

#Sat Jul 08 23:55:53 EDT 2017 url=tutoref.com username=sampleusername 

Read from a properties file​

import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class PropertiesFileSample   final private static String PROPERTIES_FILE_PATH="config.properties";  public static void main(String[] args)   Properties properties = new Properties();  // using java 8 try-with-resources structure  // so the input stream will be closed automatically  try(InputStream inputStream = new FileInputStream(PROPERTIES_FILE_PATH))   // read a value  String url = properties.getProperty("url");  // display the value  System.out.println(url);  > catch (IOException e)  e.printStackTrace();  >  > > 

Load properties from classpath

import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class PropertiesFileSample   final private static String PROPERTIES_FILE_PATH="config.properties";  public static void main(String[] args)   Properties properties = new Properties();  // using java 8 try-with-resources structure  // so the input stream will be closed automatically  try(  InputStream inputStream=  PropertiesFileSample.class.getResourceAsStream(PROPERTIES_FILE_PATH)  )   // load the properties  properties.load(inputStream);  // read a value  String url = properties.getProperty("url");  // display the value  System.out.println(url);  > catch (IOException e)  e.printStackTrace();  >  > > 

If you want to load the properties file from a non-static method, you should use the following:

InputStream is = getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE_PATH); 

Источник

Java.util.Properties.load() Method

The java.util.Properties.load(InputStream inStream) method reads a property list (key and element pairs) from the input byte stream. The input stream is in a simple line-oriented format as specified in load(Reader) and is assumed to use the ISO 8859-1 character encoding; that is each byte is one Latin1 character.

Declaration

Following is the declaration for java.util.Properties.load() method

public void load(InputStream inStream)

Parameters

inStream − the input stream.

Return Value

This method does not return a value.

Exception

  • IOException − if an error occurred when reading from the input stream.
  • IllegalArgumentException − if the input stream contains a malformed Unicode escape sequence.

Example

The following example shows the usage of java.util.Properties.list() method.

package com.tutorialspoint; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.*; public class PropertiesDemo < public static void main(String[] args) < Properties prop = new Properties(); String s = "Height=200"; String s2 = "Width=15"; try < // create a new input and output stream FileOutputStream fos = new FileOutputStream("properties.txt"); FileInputStream fis = new FileInputStream("properties.txt"); // write the first property in the output stream file fos.write(s.getBytes()); // change the line between the two properties fos.write("\n".getBytes()); // write next property fos.write(s2.getBytes()); // load from input stream prop.load(fis); // print the properties list from System.out prop.list(System.out); >catch (IOException ex) < ex.printStackTrace(); >> >

Let us compile and run the above program, this will produce the following result −

-- listing properties -- Width=15 Height=200

Источник

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