List<URL> resources = new ArrayList<>();
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> importedResources = classLoader.getResources("META-INF/services");
while (importedResources.hasMoreElements()) {
resources.add(importedResources.nextElement());
}
Map<String, String> fileContents = Maps.newHashMap();
for (URL resource : resources) {
InputStream stream = classLoader.getResourceAsStream(resource.getFile());
Properties props = new Properties(); // for debug
props.load(stream); // for debug
BufferedReader reader = new BufferedReader(new InputStreamReader(resource.openStream()));
String line;
while ((line = reader.readLine()) != null) { // Line is always null except for the declarations in my own project
String fileName = line;
if (!fileName.endsWith("/")) {
URL fileUrl = new URL(resource + "\\" + fileName);
BufferedReader fileReader = new BufferedReader(new InputStreamReader(fileUrl.openStream()));
StringBuilder content = new StringBuilder();
String fileLine;
while ((fileLine = fileReader.readLine()) != null) {
content.append(fileLine);
}
fileReader.close();
fileContents.put(fileName, content.toString());
}
}
}
System.out.println(fileContents);
} catch (IOException e) {
throw new RuntimeException(e);
}
I have been trying to read the service declaration files in my project (then saving them as a Map with Interface name as key and provider names as value), including the ones from imported Jars, but got stuck at reading files from inside JARS. Rhe URL resources will load correctly and importedResources does contain the URI to the files but when trying to readLine it will return null.
Project is Maven, URLs look something like this:
jar:file:/C:/Users/xxx/.m2/repository/org/glassfish/hk2/hk2-locator/2.5.0-b42/hk2-locator-2.5.0-b42.jar!/META-INF/services
Any suggestions? or is there a different approach instead?