Code, JavaEE

Loading Files : Classpath and Filepath

// There is a difference between getting a file from the filepath and the classpath

public Map<String, Object> loadJsonFromFilePath(String filePath) throws IOException {
 JsonReader reader =
 new JsonReader(
 new InputStreamReader(
 new FileInputStream(new File(filePath))));
 Map<String, Object> map;
 Gson gson = new Gson();
 map = gson.fromJson(reader, Map.class);

return map;

public Map<String, Object> getJsonFromClasspath(String filePath) {
 InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filePath);

 if( inputStream == null )
 {"getResourceAsStream() returned null for " + filePath );
 return null;

 Gson gson = new Gson();
 Map<String, Object> jsonMap = null;

try {
 InputStreamReader reader = new InputStreamReader(inputStream);

 if( reader == null )
 {"Could not get reader for : " + filePath );
 return null;

 JsonReader jsonReader = new JsonReader(reader);
 while (jsonReader.hasNext()) {
 jsonMap = gson.fromJson(jsonReader, Map.class);
 } catch (IOException e) {"Could not get JSON from file", e.toString());

return jsonMap;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s