Java Read a Text File Using Properties
I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 years. I like video games and reading books.
1. Introduction to Java.Util.Properties Form
Most of the enterprise applications settings are actually loaded during the awarding startup itself and the application beliefs is controlled by the awarding settings persisted in a Flat file or Registry or Database etc.
In this example, we are going to create application property file chosen "MyApp.Properties" and going store the application settings into that file. We will also read the persisted properties from that file and display that in the Console Window.
2. Key&Value Pairs of Properties
The "Properties Class" of Coffee is used to maintain one or more properties that tin can be easily streamed into Text or Binary. Each property is a Key & Value pair. Now, let us create three Property Values and shop that in a Java's Backdrop object called AppProps. This instance requires set up of Coffee Packages and the code given below shows those imports:
//Sample 01: Package inclusion import java.io.IOException; import java.nio.file.Files; import java.util.Properties; import java.nio.file.Path; import coffee.nio.file.Paths; import coffee.io.Writer; import coffee.io.Reader; At present look at the screenshot below:
Adding Java Property to Properties Instance
Author
Hither, get-go, we are creating a Java Properties object chosen AppProps which volition agree awarding properties (Marked as 1). In one case the object is on paw, we are storing iii properties by calling its "setProperty()" method.
The "setProperties()" method accepts two strings and forms Key-Value Pair. Afterwards, the Value tin be retrieved past providing the corresponding Key.
The two parameters passed to it is "Key and Value" pair. For example, the third property nosotros are adding is "FontSize" and the Size of the font is 12. Here, "FontSize" is the Key (Marked as ii) which is passed every bit First Parameter and 12 is the value for it which is passed as second parameter (Marked as three). So, in the code snippet, we created 3 application settings and stored that in a Properties object called AppProps.
Listing 1: Creating Application Settings
//Case 01: Create List of Holding Values Backdrop AppProps = new Properties(); AppProps.setProperty("Backcolor", "White"); AppProps.setProperty("Forecolor", "Blue"); AppProps.setProperty("FontSize", "12"); The "store()" method of the Java's Backdrop Class Persists Key-Value pair to Disc and the "load()" method will read the persisted information from the disc and forms the Primal-Value Pair
3. Storing Application Backdrop Using "Properties::store()" Method
The awarding properties contained in the Properties Class instance tin be persisted to a text file. The "store()" method of the Properties Class is used to save the application properties to a text file. This method takes an OutputStream or Author object to store the information. Since it accepts OutputStream as well equally Writer, in place of a text file, i tin write the properties in a binary file also. The most preferred manner is writing information technology to a text file and preferred extension for the belongings file is ".properties" . We tin can persist the information in an XML file also.
Now have a look at the Screenshot beneath:
Persisting Properties to Text File using Store() method
Writer
Commencement, we are getting Path to our ".properties file" by making utilize of the "static get() method" call of the Paths Utility Course (Marked equally 1). A Write object PropWriter is then created past calling another utility function "newBufferedWriter()". This function takes Path to our properties file (Marked as 2).
Read More From Owlcation
Now, we accept our Author object and Path object are ready. Nosotros are making calls to the Store() method of the Properties class by supplying the Writer object to it (Passed as the first parameter, marked as 3). We are also passing the comment text "Application Properties" as the 2d parameter (Marked as 4) and this text appears every bit comment text in the output file.
Once the properties are written to the text file, the content looks equally shown beneath:
Content of MyApp Properties File
Author
The comment passed to the store method appears every bit the first line in the properties file (Marked as i) and there are date and time stamp (marked equally 2) those tell when the properties are persisted. Every bit these two lines are comment lines, we tin can see # is prefixed. The bodily backdrop are persisted every bit "Key & Value" pairs which are marked as 3 in the above screenshot. Note that the default format of a single holding is "Key=Value" .
We can too hand-code and create the properties file. Follow the beneath guidelines:
- Key and Value pairs can exist created one per line.
- Use the "=" or ":" as a separator betwixt Cardinal & Value.
- To have = or: in key and/or value, use the escape char \.
- To identify comment, prefix the line with # or ! symbol.
- To organize a grouping of properties use comment heading and a bare line at the end of the group.
Listing ii: Writing the Backdrop to Text File
//Instance 02: Store Backdrop to MyApp.Properties Path PropertyFile = Paths.get("MyApp.Backdrop"); endeavor { Writer PropWriter = Files.newBufferedWriter(PropertyFile); AppProps.store(PropWriter, "Application Properties"); PropWriter.close(); } catch(IOException Ex) { Organisation.out.println("IO Exception :" + Ex.getMessage()); } four. Loading Properties from Text File Using "Properties::load()" Method
We used "Writer Text Stream" for storing the Application settings in the properties file. At present, nosotros are going to use "Reader Stream" to read the Property settings from the file. Once the backdrop are read from the ".Properties" to Java's "Backdrop Class" instance, we will display the holding settings in the Console Output Window. Below is the code snippet for this:
Reading Coffee Backdrop From Text File
Author
Commencement, we are creating the "Reader" instance PropReader by making use of the "newBufferedReader()" method (Marked every bit 1). Note that we are reusing the PropertyFile instance which we used for writing the application properties. Most of the Fourth dimension, the property files are created manually and we can utilize this aforementioned approach to read the file.
We are using the "load() method" of the Properties Course to load the Backdrop stored in the MyApp.Properties file through the passed-in Reader object called PropReader (Marked as 2). Afterward "load()" phone call, we have the all the property settings loaded into Backdrop Class instance chosen AppProps.
The "getProperty()" method of Properties Form takes the Key and returns the Value associated to that Central. In our example, we are calling this method three times and press the returned result in the Console Output Window (Marked as three – 6). Beneath is the Consummate code Case and Its Output.
Reading and Writing Java Property File - Complete Code Example
//Sample 01: Packet inclusion import java.io.IOException; import coffee.nio.file.Files; import java.util.Properties; import java.nio.file.Path; import java.nio.file.Paths; import java.io.Writer; import java.io.Reader; public grade Master { public static void main (String[] args) { //Example 01: Create List of Holding Values Backdrop AppProps = new Properties(); AppProps.setProperty("Backcolor", "White"); AppProps.setProperty("Forecolor", "Blue"); AppProps.setProperty("FontSize", "12"); //Example 02: Store Backdrop to MyApp.Properties Path PropertyFile = Paths.get("MyApp.Properties"); try { Author PropWriter = Files.newBufferedWriter(PropertyFile); AppProps.store(PropWriter, "Awarding Properties"); PropWriter.close(); } catch(IOException Ex) { System.out.println("IO Exception :" + Ex.getMessage()); } //Instance 03: Load Properties from MyApp.Properties endeavour { //3.1 Load properties from File to Holding // object Reader PropReader = Files.newBufferedReader(PropertyFile); AppProps.load(PropReader); //three.two Read Property and Brandish it in Console System.out.println("Application BackColor:" + AppProps.getProperty("Backcolor")); System.out.println("Awarding ForeColor:" + AppProps.getProperty("Forecolor")); System.out.println("Application Font Size:" + AppProps.getProperty("FontSize")); //3.3 Close the Reader File PropReader.close(); } catch(IOException Ex) { System.out.println("IO Exception :" + Ex.getMessage()); } } } Output of the Code Example
Output of the Lawmaking Instance
Author
v. Decision
The Java Programmers usually pick ".Properties" as file extension which persists the Coffee Properties to a Text file. We saw the usage of the shop() and load() methods of the Java'due south "Properties Course" and how it stores and retrieves the application properties from the ".properties" file. Since the Coffee ".Backdrop" files are usually ASCII Standard text files we used Java's Reader and Writer objects.
In this instance, we saw Backdrop persisted as a text file. The Java's Properties course supports storing and retrieving the data from XML File as well through APIs "loadFromXml()" and "storeToXML()".
Source: https://owlcation.com/stem/Java-Examples-Application-Properties-Persisted-as-Simple-Text-File
Post a Comment for "Java Read a Text File Using Properties"