Read Property File

JAVA servlet read properties file display it using JSP

In this tutorial we are going to create a simple Java servlet with the option to read a property file. Once that is done our next step is to create a JSP and use jsp:include directive to display the servlet within JSP.

Let us start by creating a Java file with some name, here I am using property.java . I have saved this file inside WEB-INF/classes folder. My application name is ReadProperty

import java.util.Properties; import java.io.*; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.annotation.*; // Tomcat 10 @WebServlet("/readprop") public class property extends HttpServlet < public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < PrintWriter out = response.getWriter(); Properties prop = new Properties(); InputStream input = null; try < input = getServletContext().getResourceAsStream("/WEB-INF/properties/server.properties"); out.println(""); // load a properties file prop.load(input); // get the property value and print it out out.println(prop.getProperty("APPNAME")); out.println("

"); out.println(prop.getProperty("DATA")); > catch (IOException ex) < //ex.printStackTrace(); out.println(ex); >finally < if (input != null) < try < input.close(); >catch (IOException e) < e.printStackTrace(); >> > > >

The property file we are using is server.properties and I am calling it using

input = getServletContext().getResourceAsStream("/WEB-INF/properties/server.properties");

As you can see I have a properties folder inside my WEB-INF

Content of the server.properties file is

APPNAME=Test Application DATA=Database

Compile the Java code and make sure there is no error.

Using Annotation WebServlet

As you might have noticed in the above code we are calling HttpRequest to using URL “ /readprop ” via annotation @WebServlet(«/readprop») , which is applicable to Tomcat 7 onwards. In other words, the full URL shall be http://ip_addr:port//readprop to trigger this HttpRequest

Using web.xml

Now add the below xml code to your existing web.xml file

property property property /property 

Create JSP file to load servlet

On your application root directory create a file name load_props.jsp

     

Reading Property File Values

In the above code I am including /readprop which is the webservlet annotation. If you don’t want to use that make sure to update the include page directive to /property or any class name you have given in the web.xml file.

Load your web application http://app:8080/ReadProperty/load_props.jsp

The result will be similar to this

Источник

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!

Источник

Java Properties File: How to Read config.properties Values in Java?

.properties is a file extension for files mainly used in Java related technologies to store the configurable parameters of an application. They can also be used for storing strings for Internationalization and localization; these are known as Property Resource Bundles.

Each parameter is stored as a pair of strings, one storing the name of the parameter (called the key/map ), and the other storing the value.

Below is a sample Java program which demonstrate you how to retrieve/read config.properties values in Java. For update follow this tutorial.

We will create 3 files:

  1. CrunchifyReadConfigMain.java
  2. CrunchifyGetPropertyValues.java
  3. config.properties file

Main Class (CrunchifyReadConfigMain.java) which will call getPropValues() method from class CrunchifyGetPropertyValues.java .

Let’s get started:

Step-1: Create config.properties file.

  1. Create Folder “ resources ” under Java Resources folder if your project doesn’t have it.
  2. create config.properties file with below value.

How to read config.properties in Java - Crunchify Tips

/Java Resources/config.properties file content:

#Crunchify Properties user=Crunchify company1=Google company2=eBay company3=Yahoo

Step-2

Create file CrunchifyReadConfigMain.java

package crunchify.com.tutorial; import java.io.IOException; /** * @author Crunchify.com * */ public class CrunchifyReadConfigMain < public static void main(String[] args) throws IOException < CrunchifyGetPropertyValues properties = new CrunchifyGetPropertyValues(); properties.getPropValues(); >>

Step-3

Create file CrunchifyGetPropertyValues.java

package crunchify.com.tutorial; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Properties; /** * @author Crunchify.com * */ public class CrunchifyGetPropertyValues < String result = ""; InputStream inputStream; public String getPropValues() throws IOException < try < Properties prop = new Properties(); String propFileName = "config.properties"; inputStream = getClass().getClassLoader().getResourceAsStream(propFileName); if (inputStream != null) < prop.load(inputStream); >else < throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath"); >Date time = new Date(System.currentTimeMillis()); // get the property value and print it out String user = prop.getProperty("user"); String company1 = prop.getProperty("company1"); String company2 = prop.getProperty("company2"); String company3 = prop.getProperty("company3"); result = "Company List = " + company1 + ", " + company2 + ", " + company3; System.out.println(result + "\nProgram Ran on " + time + " by user=" + user); > catch (Exception e) < System.out.println("Exception: " + e); >finally < inputStream.close(); >return result; > >

Step-4

Run CrunchifyReadConfigMain and checkout result.

Company List = Google, eBay, Yahoo Program Ran on Mon May 13 21:54:55 PDT 2013 by user=Crunchify

As usually happy coding and enjoy. Do let me know if you see any exception. List of all Java Tutorials.

Are you running above program in IntelliJ IDE and getting NullPointerException?

Please follow below tutorial for fix.

If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion.

Suggested Articles.

Источник

Читайте также:  Codes for html colours
Оцените статью