One of your services needs a content of a file located at your web application's context folder. More specifically, the file we want to read is in the config folder under the context directory.

AppModule.java

public static TownNames buildTownNames(Context context, final Logger log) {
    return new TownNamesImpl(context, log);
}

TownNames.java is a very simple interface:

public interface TownNames {
    List<String> getAll();
}

And the implementation (TownNamesImpl.java) which demonstrates reading a file named towns.txt from the config folder under the web app context folder:

public class TownNamesImpl implements TownNames {

    private List<String> townNames = new ArrayList<String>();

    public TownNamesImpl(Context context, Logger log) {
        String town = null;
        Resource configFile = new ContextResource(context, "config/towns.txt");
        try {
            InputStream is = configFile.openStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf8"));

            while ((town = br.readLine()) != null) {
                townNames.add(town);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public List<String> getAll() {
        Collections.sort(townNames);
        return Collections.unmodifiableList(townNames);
    }

}
  • No labels