Properties
file
1. The properties file is a simple text file
2. Properties file contains keys and values
3. All the properties file are saved with the ".properties" extension
4. properties file is always used to store the
configuration data or settings
Write Properties into properties file
package com.jsl.examples; import java.io.FileOutputStream; import java.util.Properties; public class WritingProperties { public static void main(String[] args) { Properties properties=new Properties(); FileOutputStream fos=null; try { System.out.println("Hello"); fos=new FileOutputStream("connconfig.properties"); properties.setProperty("username", "Lakshman"); properties.setProperty("password", "Lakshman"); properties.store(fos,"User information example"); fos.close(); } catch (Exception e) { e.printStackTrace(); } } }
Reading properties
package com.jsl.examples; import java.io.FileInputStream; import java.util.Properties; public class ReadingProperties { public static void main(String[] args) { FileInputStream fis=null; Properties properties=null; try{ fis=new FileInputStream("connconfig.properties"); properties=new Properties(); properties.load(fis); System.out.println("User name :"+properties.getProperty("username")); System.out.println("Password :"+properties.getProperty("password")); fis.close(); }catch (Exception e) { e.printStackTrace(); } } }
Spring Framework
Reading
Properties file values and setting bean properties in spring framework
userinfo.properties
user.email=lakshman@gmail.com
user.password=lakshman
User.java
package com.cg.example; public class User { private String email; private String password; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
User.xml
user.properties
Manager.java
package com.cg.example; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("user.xml"); User user=(User) context.getBean("user"); System.out.println(user.getEmail()); System.out.println(user.getPassword()); } }
Output :
lakshman@gmail.com
lakshman
No comments:
Post a Comment