I have an App Engine servlet which creates objects based on a JSON file (stored in a "Resources" folder under WEB-INF). I handle the parsing of the file in a separate class:
public class EventParser
{
static Gson gson = new Gson();
static String fileName = "/SOServices-war/src/main/webapp/WEB-INF/Resources/mockEvents.json";
static File file = new File(fileName);
public static List<Event> readDataFromJSON() throws IOException
{
InputStreamReader inReader = new InputStreamReader(new FileInputStream(file), "UTF-8");
String stringFromRes = null;
try (BufferedReader br = new BufferedReader(inReader))
{
StringBuilder sb = new StringBuilder();
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null)
{
sb.append(sCurrentLine);
sb.append(System.lineSeparator());
}
stringFromRes = sb.toString();
}
catch (IOException e)
{
e.printStackTrace();
}
List<Event> events = new ArrayList<Event>();
Type listOfTestObject = new TypeToken<List<Event>>(){}.getType();
events = gson.fromJson(stringFromRes, listOfTestObject);
return events;
}
}
It is important to point out that this used to work using "WEB-INF/" as path, but I've recreated the project (using the new Maven tutorial) and it has a new folder structure: instead of /war/WEB-INF, it looks like /AppName-war/src/main/webapp/WEB-INF. I don't really understand how it could affect things, but I can't seem to get file reading working again. So far I've tried:
- just using " instead of "WEB-INF/"
- putting the files under the webapp folder directly
- using the old method
- using the string provided in this code snipped, but without the dash at the beginning
Neither of them worked, the files couldn't be found on local development environment (app is not deployed yet).
Update
Big thanks to McDowell for providing me the link, it was a bit different, but it helped a lot. I am now calling the readDataFromJSON() method with a servletContext parameter like so:
List<Event> events = EventParser.readDataFromJSON(this.getServletContext());
And then in the parser:
String filePath = context.getRealPath(fileName);
InputStreamReader inReader = new InputStreamReader(new FileInputStream(new File(filePath)), "UTF-8");
This solves my issue.