Home > Tutorial > Java Json FileWriter Sample Code

Java Json FileWriter Sample Code

Writing a file is pretty common for a Java programmer. Java has built in classes and methods that make writing data to files really simple.

The Java code snippet below defines an output file to write data into. To be consistent, I decided to use Json format for the output file. I have included the contents of the written Json file below as well as standard out print statments.

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 FileWriter Source Code:

package com.jcd.java.tutorials;

import java.io.FileWriter;
import org.json.simple.JSONObject;


public class JsonSimpleFileWriter {
	
	public static void main( String[] args )
	{
		String jsonFileOut = "C:\\Users\\Admin\\Documents\\output\\SampleJsonFileOut.json";

		FileWriter fileWriter = null;
		JSONObject jsonObject = new JSONObject();
		
		jsonObject.put("DummyConfig1", "CONFIG-ONE");
		jsonObject.put("DummyConfig2", "CONFIG-TWO");
		jsonObject.put("DummyConfig3", 3);
		jsonObject.put("DummyConfig4", 4);
		
		try 
		{
			fileWriter = new FileWriter(jsonFileOut);
			fileWriter.write(jsonObject.toString());
			fileWriter.flush();
			fileWriter.close();
		}
		catch(Exception ex)
		{
			System.out.println("Exception:"+ex.toString());
		}
		
		System.out.println("File Written: "+jsonFileOut);
		
	}

}


Contents of SampleJsonFileOut.json file:

{
"DummyConfig1":"CONFIG-ONE",
"DummyConfig3":3,
"DummyConfig2":"CONFIG-TWO",
"DummyConfig4":4
}


Output after running sample code:

File Written: C:\Users\Admin\Documents\output\SampleJsonFileOut.json



Java References:

  1. Java FileWriter Class
  2. Java Json FileReader 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