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:


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();
			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());
		catch(Exception ex) 


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

Java References:

  1. Java FileReader Class
  2. Java Json FileWriter Sample Code

Add a Comment

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