Properties in JAVA

Properties class in java.util.Properties package is used to store and load key value in the properties object. The key and value is saved in file which is managed by input output stream.

Once we store value in Properties can use in future. This is kind of persisting key value object.

Create Properties object and store in File

To store file of Properties object. we have to use FileOutputStream. Before it we have to create key values in Properties by setProperty() method.

<%@ page language="java" %>
<%@ page import="java.util.Properties,java.io.FileOutputStream"%>
<%
  Properties pro=new Properties();

  pro.setProperty("my.key.name","properties_file"); 
  pro.setProperty("my.key.class","Properties"); 
  pro.setProperty("my.key.package","java.util"); 
  
  FileOutputStream fos=new FileOutputStream("my.dat");
  
  pro.store(fos,"New Properties File");
%>
<html>
<head>
<title>Properties in java</title>
</head>
<body>
Stored properties object in java
</body>
</html>

Load and read key from Properties object with FileInputStream

To load and read of Properties object have to load file first before reading key values from Properties. The file we have saved eariler and have to load with same name.

<%@ page language="java"%>
<%@ page import="java.util.Properties,java.io.FileInputStream"%>
<%
    Properties pro=new Properties();
    FileInputStream fis=new FileInputStream("my.dat");
    
    pro.load(fis);
%>
<html>
<head>
<title>Properties in java</title>
</head>
<body>
 <%=pro.getProperty("my.key.name") %><br>
 <%=pro.getProperty("my.key.class") %><br>
 <%=pro.getProperty("my.key.package") %>
</body>
</html>
Bookmark  

 

Leave a Reply

Security Code:

 

  Random Post