Code, JavaEE

Loading Files : Classpath and Filepath


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

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

return map;
 }
// CLASSPATH:

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

 if( inputStream == null )
 {
 LOG.info("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 )
 {
 LOG.info("Could not get reader for : " + filePath );
 return null;
 }

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

return jsonMap;
 }

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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