Reputation: 2554
I have this code in my CacheInitializer
which implements ServletContextListener
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
File file = new File(classLoader.getResource("synonyms.txt").getFile());
if (file != null && file.exists()) {
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String leftHand = line.split("=>")[0];
String rightHand = line.split("=>")[1];
for (String s : leftHand.split(",")) {
if (s.equals(""))
continue;
synonymsLookupMap.put(s.trim(), rightHand.trim());
}
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
throw new RuntimeException("Synonyms file not found");
}
sysnonyms.txt
file resides inside resources folder. When I try to run this code locally (Mac OSX), it runs perfectly fine. But when I deploy the same war on my Amazon Linux EC2 machine, no contents are read. I tried remote debug and code never enters the while loop. No exception is thrown either. It finds the file but behaves as if its empty, and there are no lines to be read. I tried creating synonyms.txt through vi on server and then using that to see if it was a file format issue. It did not work either.
Any idea what must be the issue?
Upvotes: 0
Views: 120
Reputation: 310909
Resources are not files. The resource API can deliver you either a URL or an InputStream for the resource. That's all you need. Just construct the Scanner directly from the input stream. The diversion via File is redundant and pointless and will not work.
Upvotes: 1