Pass in the File to Java Application to Read
- Details
- Written past
- Last Updated on 17 May 2020 | Print Email
This tutorial will help you getting how to employ the Backdrop form for reading and writing configuration for your Java applications. And at the end, we have a sample Swing awarding that demonstrates reading and writing configuration for database settings.
Table of content:
-
- Creating a Properties object
- Loading properties file
- Getting properties values
- Setting properties values
- Saving properties file
- Sample Swing application
The java.util.Backdrop class provides API for reading and writing properties in course of central=value pairs. The properties file can be either in plainly text (.properties) format or XML format. For example:
.backdrop format XML format
First, let'southward look at two pocket-sized examples:
- Loading properties file and reading a belongings's value
The following lawmaking loads config.properties file and read out a belongings chosen "host":
File configFile = new File("config.properties"); endeavour { FileReader reader = new FileReader(configFile); Properties props = new Backdrop(); props.load(reader); String host = props.getProperty("host"); System.out.print("Host name is: " + host); reader.close(); } take hold of (FileNotFoundException ex) { // file does not be } catch (IOException ex) { // I/O mistake }
- Setting the property'south value and salve the properties file
The following code writes value of a property to the config.backdrop file:
File configFile = new File("config.backdrop"); effort { Properties props = new Properties(); props.setProperty("host", "www.codejava.internet"); FileWriter writer = new FileWriter(configFile); props.shop(writer, "host settings"); writer.close(); } catch (FileNotFoundException ex) { // file does non exist } catch (IOException ex) { // I/O error }
Now let's dive into more details for each step: initialize, load, go, ready and relieve.
1. Creating a Properties object
- Create a Propertiesobject by using empty constructor:
Properties props = new Properties();
- Create a Backdrop object by supplying a default properties listing:
Backdrop defaultProps = new Properties(); // ready default properties... // create main Properties object Properties props = new Backdrop(defaultProps);
The default Backdrop object would exist useful if you lot desire to have a list of default properties which can be used when some properties practise not exist in the concrete file.
2. Loading properties file
We can load the backdrop file (.properties or XML) using either subclasses of java.io.Reader class or coffee.io.InputStream class. Following are some examples:
- Load backdrop from a .backdrop file using a FileReader object:
File configFile = new File("config.backdrop"); FileReader reader = new FileReader(configFile); Properties props = new Properties(); // load the backdrop file: props.load(reader);
The file config.properties must exist in the program's directory. Of course we tin specify accented path of the configuration file. - Load properties from a plain text file using an InputStream object:
File configFile = new File("config.properties"); InputStream inputStream = new FileInputStream(configFile); Properties props = new Properties(); props.load(inputStream);
- If XML is your required format, use the loadFromXML() part:
props.loadFromXML(reader);
Or:
props.loadFromXML(inputStream);
- If the backdrop file is placed in plan's classpath (i.e. in the source package construction or in a jar file), load the input stream as follows:
InputStream inputStream = MyProgram.grade.getResourceAsStream("/internet/codejava/config/config.properties"); Backdrop props = new Backdrop(); props.load(inputStream);
Notation: the methods load() or loadFromXML() exercise not shut the reader nor the input stream, then you should close them afterward:
reader.close();
Or:
inputStream.close();
3. Getting backdrop values
The Backdrop form has ii methods for retrieving value of a property in the properties file:
-
- String getProperty(String central) : returns value of the belongings specified past the given key. It returns nil if the key not plant.
- String getProperty(Cord fundamental, String defaultValue) : like the above method, just this method will render a default value if the key non constitute.
The following statement gets value of a property whose key is "host":
Cord host = props.getProperty("host");
And the following statement will render the default value "localhost" if the holding non found:
String host = props.getProperty("host", "localhost");
NOTE: The method getProperty() searches in the current property list (loaded from the properties) file, then in the default properties list (if specified when constructing the Properties object).
iv. Setting properties values
Setting value for a specific holding is pretty simple, using this sole method:
Object setProperty(String key, String value)
This method returns previous value of the property specified past the given fundamental.
Instance:
props.setProperty("host", "www.codejava.net");
NOTE: the method setProperty() does non update the properties file, information technology just updates the internal properties list.
5. Saving properties file
To save the properties into the file permanently, use the shop() method for plain text file and storeToXML() method for XML file. And we take to supply either a java.io.Writer object or an OutputStream object to these methods and likewise a comment text. Following are some examples:
- Save to plain text file using a Authorobject:
File configFile = new File("config.properties"); FileWriter writer = new FileWriter(configFile); props.store(writer, "host settings");
- Save to XML file using an OutputStream object:
File configFile = new File("config.xml"); OutputStream outputStream = new FileOutputStream(configFile); props.storeToXML(outputStream, "host settings");
NOTE: the methods shop() or storeToXML() do not close the author nor the output stream, then you should close them explicitly:
writer.shut();
Or:
outputStream.close();
6. Sample Swing application
To demonstrate the usage of Properties class, nosotros create a Swing-based application looks like this:
On startup, the program will try to load properties from config.properties file. If the file has not existed before, it will use the default properties. When clicking on the Salve button, the properties values will be stored in the config.properties file.
You can download the programme's source code and executable jar file in the attachments department.
Other Java Coding Tutorials:
- ten Common Mistakes Every Beginner Coffee Developer Makes
- 10 Java Core Best Practices Every Java Programmer Should Know
- How to become a good developer? 13 tasks you should exercise now
- How to calculate MD5 and SHA hash values in Coffee
- How to generate random numbers in Coffee
- Java File Encryption and Decryption Example
Virtually the Writer:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the fourth dimension of Java i.4 and has been falling in love with Java since so. Make friend with him on Facebook and watch his Coffee videos you YouTube.
Add annotate
Source: https://www.codejava.net/coding/reading-and-writing-configuration-for-java-application-using-properties-class
0 Response to "Pass in the File to Java Application to Read"
Post a Comment