Convert String to Properties in Java
In this example, we will show you simple program about, how to convert string to properties in Java. The example has been tested and verified, the same has been shared in the post.
Example Program
package com.dineshkrish; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.Properties; /** * * @author Dinesh Krishnan * */ public class Program { public static Properties convert(final String str, final String delimiter) throws IOException { Properties properties = new Properties(); if (str != null && !str.isEmpty()) { Reader reader = new StringReader(str.replace(delimiter, "\n")); properties.load(reader); } return properties; } public static void main(String[] args) { String str1 = "first.name=Dinesh,last.name=Krishnan,country=India,email.id=info@idineshkrishnan.com"; String str2 = "first.name=Dinesh|last.name=Krishnan|country=India|email.id=info@idineshkrishnan.com"; String str3 = "first.name=Dinesh$last.name=Krishnan$country=India$email.id=info@idineshkrishnan.com"; try { Properties properties1 = convert(str1, ","); Properties properties2 = convert(str2, "|"); Properties properties3 = convert(str3, "$"); System.out.println("Properties 1: "+properties1); System.out.println("Properties 2: "+properties2); System.out.println("Properties 3: "+properties3); } catch (IOException e) { e.printStackTrace(); System.out.println(e.getMessage()); } } }
Output
Properties 1: {last.name=Krishnan, first.name=Dinesh, country=India, email.id=info@idineshkrishnan.com} Properties 2: {last.name=Krishnan, first.name=Dinesh, country=India, email.id=info@idineshkrishnan.com} Properties 3: {last.name=Krishnan, first.name=Dinesh, country=India, email.id=info@idineshkrishnan.com}
References
1. https://docs.oracle.com/javase/8/docs/api/java/util/Properties.html
2. https://docs.oracle.com/javase/8/docs/api/java/io/StringReader.html
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet