I keep getting Java heap space
error when storing JSON object to file. The input file is 180 MB.
I am creating a JSON Object which consist of JSON array of JSON Objects. I always come across this error when working on files which are not that large.
What would be the best method to store such objects to file ?
public class ProcessData {
public static void createJson(String path) throws Exception
{
BufferedReader br = new BufferedReader(new FileReader(path));
FileWriter fw = new FileWriter("restaurants.json");
try
{
JSONObject storeObj = new JSONObject();
JSONArray restaurantArray = new JSONArray();
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null)
{
JSONObject obj = new JSONObject();
String[] vals = line.split("\\t");
obj.put("id", vals[0]);
String[] tempvals = vals[1].split("\\|");
String[] details = tempvals[0].split(",");
obj.put("name", details[0]);
sb.setLength(0);
sb.append(details[2]);
sb.append(", ");
sb.append(details[3]);
sb.append(", ");
sb.append(details[1]);
sb.append(", ");
sb.append(details[4]);
String address = sb.toString();
address.replace("\\s+", " ");
obj.put("address", address);
JSONArray arr = new JSONArray();
for (int i = 0; i < tempvals.length; ++i)
{
JSONObject objtemp = new JSONObject();
details = tempvals[i].split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
objtemp.put("inspectionDate", details[7]);
objtemp.put("code", details[9]);
objtemp.put("description", details[10]);
objtemp.put("score", details[12]);
objtemp.put("grade", details[13]);
objtemp.put("gradeDate", details[14]);
arr.add(objtemp);
}
obj.put("violationDetails", arr);
restaurantArray.add(obj);
}
storeObj.put("restaurants", restaurantArray);
fw.write(storeObj.toString());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
fw.flush();
fw.close();
br.close();
}
}
public static void main(String args[]) throws Exception {
try{
createJson("output/part-r-00000");
}
catch(Exception e){
e.printStackTrace();
}
}
}