I’m trying to run a java class that reads off some values from a JSON file. When I run it, however, I get the error:
java.io.FileNotFoundException: \file001.json (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at jsonPractice.main(jsonPractice.java:21)
The code I am using is:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class jsonPractice {
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
JSONParser parser = new JSONParser();
try
{
Object obj = parser.parse(new FileReader("file001.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
long age = (Long) jsonObject.get("age");
System.out.println(age);
JSONArray msg = (JSONArray) jsonObject.get("messages");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext())
{
System.out.println(iterator.next());
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (ParseException e) {
e.printStackTrace();
}
}
}
I’ve made sure to add the json jar to the build path and the file001.json is located inside the folder in the workspace for the project.
Thanks
You can get the current directory using –
or
Let’s consider your file is in
/home/user/test/file/file001.jsonand you are getting/home/user/test/using the current directory command(s). Then, append the restfile/file001.jsonlike –