Java read all properties files

Properties File — Java Read & Write

This tutorial explains step by step to read and write a properties file in java with example You learned to read properties file with key and values as well as line by line and also write key and values to the properties file.

In this tutorial, How to read and write a properties file content in Java

Java properties file reader example

In this example, you will learn how to read a key and its values from a properties file and display it to console

Let’s declare the properties file

Create a properties object, Properties is a data structure to store keys and values in java

Create URL object using ClassLoader . getSystemResource method

Create a InputStream using url.openStream method

Load the properties content into the java properties object using the load method

Add try and catch block for IOExceptions and FIleNotFoundException

Oneway, Print the value using getProperty with the key of a properties object

Another way is to iterate properties object for the loop

First, get all keys using stringPropertyNames

using for loop print the key and values.

 catch (FileNotFoundException fie) < fie.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >System.out.println(properties.getProperty("hostname")); Set keys = properties.stringPropertyNames(); for (String key : keys) < System.out.println(key + " - " + properties.getProperty(key)); >> > 

How to read a properties file line by line in java

  • created a File object with an absolute path
  • Create BufferedReader using FileReader object
  • get the First line of the properties file using readLine of BufferedReader
  • Loop using while loop until the end of the line reached
  • Print each line
 > catch (FileNotFoundException e1) < e1.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >finally < try < br.close(); >catch (IOException e) < e.printStackTrace(); >> > > 

How to write a key and values to a properties file in java

In this example, You can read and write a property using

  • First create a File object
  • Create a writer object using FileWriter
  • Create properties object and add new properties or update existing properties if the properties file exists
  • setProperties method do update or add key and values
  • store method of properties object writes to the properties file, You have to add the comment which appends to the properties file as a comment

Here is a complete example read and write a properties file

 catch (FileNotFoundException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >> > 

Conclusion

You learned to read a properties file with keys and values as well as line by line and also write keys and values to the properties file

Источник

Tech Tutorials

Tutorials and posts about Java, Spring, Hadoop and many more. Java code examples and interview questions. Spring code examples.

Wednesday, April 14, 2021

How to Read Properties File in Java

In this tutorial you will see how to read a properties file in Java. If you have any configurable data in your application like DB configuration, user settings its better to keep it in a properties file and read it from there. A properties file stores data in the form of key/value pair.

  1. Loading properties file from the file system. See example.
  2. Loading properties file from classpath. See example.

Project structure

For this example we’ll have a properties file named app.properties file in a folder called resource. The resource folder is at the same level at the src folder in the Java project.

Steps for reading a properties file in Java

  1. Create an instance of Properties class.
  2. Create a FileInputStream by opening a connection to the properties file.
  3. Read property list (key and element pairs) from the input stream using load() method of the Properties class.

Content of the properties file

Here the properties file used is named app.properties file with it’s content as-

user=TestUser url=https://www.netjstech.com

Loading properties file from the file system

One way to read properties file in Java is to load it from the file system.

import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class PropDemo < private Properties properties = new Properties(); public static void main(String[] args) < PropDemo pDemo = new PropDemo(); pDemo.loadPropertiesFile(); pDemo.readProperties(); >// This method is used to load the properties file private void loadPropertiesFile() < InputStream iStream = null; try < // Loading properties file from the path (relative path given here) iStream = new FileInputStream("resource/app.properties"); properties.load(iStream); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >finally < try < if(iStream != null)< iStream.close(); >> catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> > /** * Method to read the properties from a * loaded property file */ private void readProperties() < System.out.println("User name - " + properties.getProperty("user")); System.out.println("URL - " + properties.getProperty("url")); // reading property which is not there System.out.println("City - " + properties.getProperty("city")); >>
User name - TestUser URL - https://www.netjstech.com City - null

Here you can see that in the code there is an attempt to read the property “city” which doesn’t exist in the app.properties file that’s why it is retrieved as null.

Loading properties file from classpath

If you have properties file in the project classpath then you can load it by using the getResourceAsStream method. That is another way to read properties file in Java.

import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class PropDemo < private Properties properties = new Properties(); public static void main(String[] args) < PropDemo pDemo = new PropDemo(); pDemo.loadProperties(); pDemo.readProperties(); >// This method is used to load the properties file private void loadProperties() < InputStream iStream = null; try < // Loading properties file from the classpath iStream = this.getClass().getClassLoader() .getResourceAsStream("app.properties"); if(iStream == null)< throw new IOException("File not found"); >properties.load(iStream); > catch (IOException e) < e.printStackTrace(); >finally < try < if(iStream != null)< iStream.close(); >> catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> > /** * Method to read the properties from a * loaded property file */ private void readProperties() < System.out.println("User name - " + properties.getProperty("user")); System.out.println("URL - " + properties.getProperty("url")); >>
User name - TestUser URL - https://www.netjstech.com

That’s all for this topic How to Read Properties File in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Источник

Get All Keys and Values of the Properties files in Java

In this section, you will learn how to get all keys and it’s values of the properties files in Java.

Get All Keys and Values of the Properties files in Java

In this section, you will learn how to get all keys and it’s values of the properties files in Java.

Get All Keys and Values of the Properties files in Java

Get All Keys and Values of the Properties files in Java

In this section, you will learn how to get all keys and it’s values of the properties files in Java. Java provides the features to collection of all keys and values of the properties file. The properties files that can be used to large collections of information to be inserting in the properties files.

Here, you will get the all keys and values of the properties files with the help of this program. The program shows the keys and it’s values when you run it. The following methods had been used by the program.

pro.keySet():
This method returns a set of keys, which contained in the object of the Properties method. The Properties files has the many keys then this method provides all keys.

pro.keys():
This method provides the all keys of the properties files. Which stored in the Enumeration objects.

Enumeraton:
This is the interface which provided by the java.util package. It’s object implements the series of elements and calls the nextElements method, which provides the series of elements. The keys and values of the Properties files which is enumerated by this interface and calls the hashtable which defines the keys and values of the properties files.

hasMoreElements():
This method checks the Enumeration object has more elements or not and returns the true or false. It returns true, if the Enumeration object has more than one elements Otherwise, it return false.

nextElement():
This is the method to returns the next elements of the Enumeration, if the enumeration provides the more than one elements.

Here is the video tutorial of: «How to get key and value from properties file in Java?»

Here is the code of program:

import java.io.*;
import java.util.*;

public class GetAllProperties <
public static void main ( String [] args ) <
Properties pro = new Properties () ;
try <
BufferedReader br = new BufferedReader ( new InputStreamReader ( System.in )) ;
System.out.print ( «Enter file name for getting all properties : » ) ;
FileInputStream in = new FileInputStream ( br.readLine () + «.properties» ) ;
pro.load ( in ) ;
System.out.println ( «All keys of the property file : » ) ;
System.out.println ( pro.keySet ()) ;
System.out.println ( «All values of the property file : » ) ;
Enumeration em = pro.keys () ;
while ( em.hasMoreElements ()) <
String str = ( String ) em.nextElement () ;
System.out.println (str + «: » + pro.get ( str )) ;
>
>
catch ( IOException e ) <
System.out.println ( e.getMessage ()) ;
>
>
>

Tutorials

  1. Java util package Examples
  2. Java Util Package — Utility Package of Java
  3. Generating Random Number
  4. Breaking the String into Words
  5. Listing all available Locales
  6. Setting the default Locale
  7. Associate a value with an object
  8. Comparing Arrays
  9. Shuffling the Element of a List or Array
  10. Collections Framework
  11. Collection Iterate Example
  12. Converting Collection to an Array
  13. Converting an Array to a Collection
  14. Implement the Queue in Java
  15. Implementing a Stack in Java
  16. Implementing a Least-Recently-Used(LRU) Cache
  17. Creating a Copy of a Collection
  18. Making a Collection Read-Only
  19. Sorting elements of a Collection
  20. Creating a Hash Table
  21. Finding an Element in a Sorted Array
  22. Read the Key-Value of Property File in Java
  23. Get All Keys and Values of the Properties files in Java
  24. Write the Keys and Values of the Properties files in Java
  25. Scheduling a Timer Task
  26. Getting the Current Time
  27. Getting Information of All Available Time Zones
  28. Getting the current date
  29. Determining the Number of Days in a Month
  30. Comparing Dates in Java
  31. Determining the actual age from date of birth in Java
  32. Determining If a Year is a Leap Year in Java
  33. Determining the Day-of-Week for a Particular Date
  34. What is a JAR file in Java
  35. Creating a JAR file in Java
  36. Viewing contents of a JAR File
  37. Listing the Main Attributes in a JAR File Manifest
  38. Creating a ZIP file in Java
  39. Listing Contents of a ZIP File
  40. Unzip a ZIP File

Источник

Читайте также:  Загрузка css до загрузки страницы
Оцените статью