Responsive Ad Area

Share This Post

Blog Role / Featured Tutorials / Java

Reading and Writing Property Files using Java

Reading and Writing Property Files using Java

Prev post in this trail is Reading and Writing delimited files using Java
Next post in this trail is Java Fixed Width Text files using row, col type storage

In the previous articles I talked about reading and writing of delimited files. We will make our own property file API even though Java has a Properties class for this in the java.util API. A property file is a file with name=value pairs. In this first example I use = as the delimiter. I use only one line properties. each line must have name=value. Strings do not occur over multiple lines. In this first example all we do is to read the file and parse it based on the = delimiter and output results. This shows we obtain a list of strings where every other string is a name or property in the order read.

import java.util.regex.*;
import java.io.*;
public class PropertiesReader {
 private static String aFileName = "properties1.txt";
 public static void main(String[] args) {
  try (BufferedReader br = new BufferedReader(new FileReader(aFileName))) {
   String aLine;
   while ((aLine = br.readLine()) != null) {
    String[] dataRecord=aLine.split(Pattern.quote("="));
    for(int i=0;i<dataRecord.length;i++)
     System.out.println(dataRecord[i]);
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

And the file we parse which contains some info about an RPG character.

birth=2/2/2018
name=Larry the Rogue
level=10
wealth=15.25
magic=false

Next we will go ahead and make a PropertyRecord class which
will contain a name and value pair. And make a list of PropertyRecords.
We will add some utility methods to the PropertyRecord class for aiding in type conversion to and from a String form.
However the programmer using this code will have to be aware of which name contains which type and call the correct methods for conversion. And we will move that code in main method into a constructor which is the more proper way. This version does not use the setters or getters and they have
not yet been tested. In the next version we will test these methods. Also note you could add a methods for set/get of String type or the Name itself but I left the fields so that they are accessible and they are obviously String types.

import java.util.regex.*;
import java.io.*;
import java.util.*;
import java.text.*;
public class PropertiesReader {
 public class PropertyRecord{
  String name=null;
  String value=null;
  SimpleDateFormat dateFormat=new SimpleDateFormat("dd/MM/yy");
  public int getInt(){
   return Integer.parseInt(value);
  }
  public void setInt(int anInt){
   value=""+anInt;
  }
  public float getFloat(){
   return Float.parseFloat(value);
  }
  public void setFloat(int aFloat){
   value=""+aFloat;
  }
  public boolean getBoolean(){
   return Boolean.parseBoolean(value);
  }
  public void setBoolean(boolean aBoolean){
   value=""+aBoolean;
  }
  public Date getDate(){
   return new Date(value);
  }
  public void setDate(int date){
   dateFormat.format(date);
  }
  public String toString(){
   return name+"="+value;
  }
 }
 private static String aFileName = "properties1.txt";
 public PropertiesReader(){
   PropertyRecord property=null;
   ArrayList<PropertyRecord> properties = new ArrayList<PropertyRecord>();
   try (BufferedReader br = new BufferedReader(new FileReader(aFileName))) {
    String aLine;
	while ((aLine = br.readLine()) != null) {
	 String[] propertyInput=aLine.split(Pattern.quote("="));
	 property=new PropertyRecord();
	 property.name=propertyInput[0];
	 property.value=propertyInput[1];
	 properties.add(property);
	}
   } catch (IOException e) {
    e.printStackTrace();
   }
   Iterator<PropertyRecord> propertiesIterator = properties.iterator();
   while(propertiesIterator.hasNext()){
    System.out.println(propertiesIterator.next().toString());
   }
  }
 
 public static void main(String[] args) {
  new PropertiesReader();
 }
}

The output is as you would expect, the file contents reconstructed from Strings.

So next we need to test our get methods where I found an error or two. This is the corrected code and test.

import java.util.regex.*;
import java.io.*;
import java.util.*;
import java.text.*;
public class PropertiesReader {
 SimpleDateFormat dateFormat=new SimpleDateFormat("MM/dd/yy");
 public class PropertyRecord{
  String name=null;
  String value=null;
  SimpleDateFormat dateFormat=new SimpleDateFormat("MM/dd/yy");
  public int getInt(){
   return Integer.parseInt(value);
  }
  public void setInt(int anInt){
   value=""+anInt;
  }
  public float getFloat(){
   return Float.parseFloat(value);
  }
  public void setFloat(Float aFloat){
   value=""+aFloat;
  }
  public boolean getBoolean(){
   return Boolean.parseBoolean(value);
  }
  public void setBoolean(boolean aBoolean){
   value=""+aBoolean;
  }
  public Date getDate(){
   return new Date(value);
  }
  public void setDate(Date date){
   value=dateFormat.format(date);
  }
  public String toString(){
   return name+"="+value;
  }
 }
 private static String aFileName = "properties1.txt";
 public PropertiesReader(){
   PropertyRecord property=null;
   ArrayList<PropertyRecord> properties = new ArrayList<PropertyRecord>();
   try (BufferedReader br = new BufferedReader(new FileReader(aFileName))) {
    String aLine;
	while ((aLine = br.readLine()) != null) {
	 String[] propertyInput=aLine.split(Pattern.quote("="));
	 property=new PropertyRecord();
	 property.name=propertyInput[0];
	 property.value=propertyInput[1];
	 properties.add(property);
	}
   } catch (IOException e) {
    e.printStackTrace();
   }
   Iterator<PropertyRecord> propertiesIterator = properties.iterator(); 
   while(propertiesIterator.hasNext()){
    property=propertiesIterator.next(); 
    if(property.name.equals("name"))
     System.out.println("The characters name is: "+property.value);
    if(property.name.equals("birth"))
     System.out.println("The characters creation date was: "+dateFormat.format(property.getDate()));
    if(property.name.equals("level"))
     System.out.println("The character has obtained level: "+property.getInt());
    if(property.name.equals("wealth"))
     System.out.println("The character has in his purse: $"+property.getFloat());
    if(property.name.equals("magic"))
     System.out.println("The character"+((property.getBoolean())?" is ":" is not ")+"a magic user");
   }
  }
 public static void main(String[] args) {
  new PropertiesReader();
 }
}

Now, we need to test the setter methods. So the previous example will be amended to output initial results, make some changes to the records and then output new results. We will pull our stats display code out into its own displayPropertyStats method. And we will make a utility method for finding a given property.

import java.util.regex.*;
import java.io.*;
import java.util.*;
import java.text.*;
public class PropertiesReader {
SimpleDateFormat dateFormat=new SimpleDateFormat("MM/dd/yy");
 public class PropertyRecord{
  String name=null;
  String value=null;
  SimpleDateFormat dateFormat=new SimpleDateFormat("MM/dd/yy");
  public int getInt(){
   return Integer.parseInt(value);
  }
  public void setInt(int anInt){
   value=""+anInt;
  }
  public float getFloat(){
   return Float.parseFloat(value);
  }
  public void setFloat(Float aFloat){
   value=""+aFloat;
  }
  public boolean getBoolean(){
   return Boolean.parseBoolean(value);
  }
  public void setBoolean(boolean aBoolean){
   value=""+aBoolean;
  }
  public Date getDate(){
   return new Date(value);
  }
  public void setDate(Date date){
   value=dateFormat.format(date);
  }
  public String toString(){
   return name+"="+value;
  }
 }
 private static String aFileName = "properties1.txt";
 public PropertiesReader(){
   PropertyRecord property=null;
   ArrayList<PropertyRecord> properties = new ArrayList<PropertyRecord>();
   try (BufferedReader br = new BufferedReader(new FileReader(aFileName))) {
    String aLine;
	while ((aLine = br.readLine()) != null) {
	 String[] propertyInput=aLine.split(Pattern.quote("="));
	 property=new PropertyRecord();
	 property.name=propertyInput[0];
	 property.value=propertyInput[1];
	 properties.add(property);
	}
   } catch (IOException e) {
    e.printStackTrace();
   }
   Iterator<PropertyRecord> propertiesIterator = properties.iterator(); 
   displayCharacterStats(propertiesIterator);
   property=findProperty(properties,"name");
   property.value="Larry the Wizard";
   property=findProperty(properties,"birth");
   property.setDate(new Date("1/8/2018"));
   property=findProperty(properties,"level");
   property.setInt(13);
   property=findProperty(properties,"wealth");
   property.setFloat(120.97f);
   property=findProperty(properties,"magic");
   property.setBoolean(true);
   System.out.println();
   propertiesIterator = properties.iterator();
   displayCharacterStats(propertiesIterator);
   
   
  }
  public PropertyRecord findProperty(ArrayList<PropertyRecord> properties, String name){
   Iterator<PropertyRecord> propertiesIterator = properties.iterator();
   PropertyRecord property=null;
   while(propertiesIterator.hasNext()){
   	property=propertiesIterator.next(); 
    if(property.name.equals(name))return property;
   }
   return null;
  }
  public void displayCharacterStats(Iterator<PropertyRecord> propertiesIterator){
   PropertyRecord property=null;
   while(propertiesIterator.hasNext()){
    property=propertiesIterator.next(); 
    if(property.name.equals("name"))
     System.out.println("The characters name is: "+property.value);
    if(property.name.equals("birth"))
     System.out.println("The characters creation date was: "+dateFormat.format(property.getDate()));
    if(property.name.equals("level"))
     System.out.println("The character has obtained level: "+property.getInt());
    if(property.name.equals("wealth"))
     System.out.println("The character has in his purse: $"+property.getFloat());
    if(property.name.equals("magic"))
     System.out.println("The character"+((property.getBoolean())?" is ":" is not ")+"a magic user");
   }
  }
 public static void main(String[] args) {
  new PropertiesReader();
 }
}

And here is the new output.

The characters creation date was: 02/02/18
The characters name is: Larry the Rogue
The character has obtained level: 10
The character has in his purse: $15.25
The character is not a magic user

The characters creation date was: 01/08/18
The characters name is: Larry the Wizard
The character has obtained level: 13
The character has in his purse: $120.97
The character is a magic user

Next we must read change and write back to the file the new property values which will be easy at this point. We will then be done with this example. I may write an article using the Java Util Properties class and I may expand this example to include multiline Strings and who knows maybe binary data for image or sound work. The point is that you can find API's that do these things or if you don't want their complexity in your prototypes just do it yourself.

import java.util.regex.*;
import java.io.*;
import java.util.*;
import java.text.*;
public class PropertiesReaderWriter {
 SimpleDateFormat dateFormat=new SimpleDateFormat("MM/dd/yy");
 public class PropertyRecord{
  String name=null;
  String value=null;
  SimpleDateFormat dateFormat=new SimpleDateFormat("MM/dd/yy");
  public int getInt(){
   return Integer.parseInt(value);
  }
  public void setInt(int anInt){
   value=""+anInt;
  }
  public float getFloat(){
   return Float.parseFloat(value);
  }
  public void setFloat(Float aFloat){
   value=""+aFloat;
  }
  public boolean getBoolean(){
   return Boolean.parseBoolean(value);
  }
  public void setBoolean(boolean aBoolean){
   value=""+aBoolean;
  }
  public Date getDate(){
   return new Date(value);
  }
  public void setDate(Date date){
   value=dateFormat.format(date);
  }
  public String toString(){
   return name+"="+value;
  }
 }
 private static String aFileName = "properties1.txt";
 private static String outputFileName = "newproperties.txt";
 public PropertiesReaderWriter(){
   PropertyRecord property=null;
   ArrayList<PropertyRecord> properties = new ArrayList<PropertyRecord>();
   try (BufferedReader br = new BufferedReader(new FileReader(aFileName))) {
    String aLine;
	while ((aLine = br.readLine()) != null) {
	 String[] propertyInput=aLine.split(Pattern.quote("="));
	 property=new PropertyRecord();
	 property.name=propertyInput[0];
	 property.value=propertyInput[1];
	 properties.add(property);
	}
   } catch (IOException e) {
    e.printStackTrace();
   }
   Iterator<PropertyRecord> propertiesIterator = properties.iterator(); 
  
   property=findProperty(properties,"name");
   property.value="Larry the Wizard";
   property=findProperty(properties,"birth");
   property.setDate(new Date("1/8/2018"));
   property=findProperty(properties,"level");
   property.setInt(13);
   property=findProperty(properties,"wealth");
   property.setFloat(120.97f);
   property=findProperty(properties,"magic");
   property.setBoolean(true);
   
   write(properties);
   
  }
  public PropertyRecord findProperty(ArrayList<PropertyRecord> properties, String name){
   Iterator<PropertyRecord> propertiesIterator = properties.iterator();
   PropertyRecord property=null;
   while(propertiesIterator.hasNext()){
   	property=propertiesIterator.next(); 
    if(property.name.equals(name))return property;
   }
   return null;
  }
  public void displayCharacterStats(Iterator<PropertyRecord> propertiesIterator){
   PropertyRecord property=null;
   while(propertiesIterator.hasNext()){
    property=propertiesIterator.next(); 
    if(property.name.equals("name"))
     System.out.println("The characters name is: "+property.value);
    if(property.name.equals("birth"))
     System.out.println("The characters creation date was: "+dateFormat.format(property.getDate()));
    if(property.name.equals("level"))
     System.out.println("The character has obtained level: "+property.getInt());
    if(property.name.equals("wealth"))
     System.out.println("The character has in his purse: $"+property.getFloat());
    if(property.name.equals("magic"))
     System.out.println("The character"+((property.getBoolean())?" is ":" is not ")+"a magic user");
   }
  }
  public void write(ArrayList<PropertyRecord> properties) {
   try (BufferedWriter bw = new BufferedWriter(new FileWriter(outputFileName))) {
    Iterator<PropertyRecord> propertiesIterator = properties.iterator();
    while(propertiesIterator.hasNext())
     bw.write(propertiesIterator.next().toString()+"\n");
   } catch (IOException e) {
    e.printStackTrace();
   }
 }
 public static void main(String[] args) {
  new PropertiesReaderWriter();
 }
}

Prev post in this trail is Reading and Writing delimited files using Java
Next post in this trail is Java Fixed Width Text files using row, col type storage

 

Share This Post

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>