NullPointerException when reading a json file inside a jar file

85 views Asked by At

I am trying to run a class inside a jar file. Inside the java program, I have a class called CustomSearchHandler which is calling a function to read an array of strings from a JSON file called Attributes.json. Note that this JSON file is in the same directory as the class.

public class CustomSearchHandler extends SearchHandler {
    private static Logger logger = LoggerFactory.getLogger(CustomSearchHandler.class);

    public static final String CURRENCYCODEHEADER = "currencycode";

    @Override
    public void handleRequestBody(SolrQueryRequest solrRequest,
                                  SolrQueryResponse solrResponse) throws Exception {
          ArrayList<String> fixedAttributesList = fetchAttributes("fixed_attributes");

    }
  
    public static ArrayList<String> fetchAttributes(String type){
        ArrayList<String> attributesList = new ArrayList<String>();
        try{
            InputStream inputStream = CustomSearchHandler.class.getResourceAsStream("Attributes.json");
            JSONObject json = new JSONObject(new InputStreamReader(inputStream));
            JSONArray jsonArray = json.getJSONArray("fixed_attributes");
            for (int i = 0; i < jsonArray.length(); i++) {
                attributesList.add(jsonArray.getString(i));
            }
            logger.info("e");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return attributesList;
    }
}

When I create a jar from this and execute this, I get -

java.lang.NullPointerException
        at java.base/java.io.Reader.<init>(Reader.java:167)
        at java.base/java.io.InputStreamReader.<init>(InputStreamReader.java:72)
        at CustomSearchHandler.fetchAttributes(CustomSearchHandler.java:125)
        at CustomSearchHandler.handleRequestBody(CustomSearchHandler.java:60)

I just need to read the list of strings of array "fixed_attributes" and assign it to an ArrayList. Please help.

0

There are 0 answers