Home > Tutorial > Java Json FileReader Sample Code

Java Json FileReader Sample Code

Reading a file is one of those basic necessities as a Java programmer. Every Java application I developed needed a configuration file to be read at startup. The file to read can be any type, but I find myself reading mostly Json formatted files these days.

The Java code snippet below takes an Json file as the input, parse the name/value pairs, and then output that to the screen. I have included the contents of my example Json file below. Now the Json Simple library is not included with any Java library so you will need to include the library in your build path or include it as a dependency in your pom.xml if using maven.

For simplicity, I am just including the Json Simple library in my build path. You can google “json-simple” to download the jar. I am using version 1.1.1 in my example. Since I do my Java development using Eclipse, I included a screenshot on where I placed the json simple jar file.

Java Json FileReader Source Code:

package com.jcd.java.tutorials;

import java.io.FileReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimpleFileReader {
	
	public static void main( String[] args )
	{
		String jsonFile = "C:\\Users\\Admin\\Documents\\conf\\SampleJsonFileToRead.json";
		JSONParser parser = new JSONParser();
		
		try 
		{
			System.out.println("Read json file contents");
			
			Object object = parser.parse(new FileReader(jsonFile));
			JSONObject jsonObject = (JSONObject) object;
			
			String file = jsonObject.get("ConfigFile").toString();
			String type = jsonObject.get("ConfigType").toString();
			int numb = Integer.parseInt(jsonObject.get("ConfigNumber").toString());
			
			System.out.println("ConfigFile="+file);
			System.out.println("ConfigType="+type);
			System.out.println("ConfigNumber="+numb);
					
		}
		catch(Exception ex) 
		{ 
			System.out.println("Exception:"+ex.toString());
		}
		
	}

}


Contents of SampleJsonFileToRead.json file:

{

	"ConfigFile" : "/path/to/config/file.txt",
	"ConfigNumber" : 100,
	"ConfigType" : "TYPE-A"

}


Output after running sample code:

Read json file contents
ConfigFile=/path/to/config/file.txt
ConfigType=TYPE-A
ConfigNumber=100



Java References:

  1. Java FileReader Class
  2. Java Json FileWriter Sample Code
Smedley
Posted by

Smedley

Smedley has been programming in Java for about twenty years. He enjoys sharing code samples to other fellow Java coders.

You may also like...

Leave a Reply

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

Copyright © 2018 JavaCodeDepot