List the classpath with guava
I wanna use some resources on my classpath and dont know the exact path to address them. I'll show this using an example with jquery.
I have dependency and want to use the jquery inside.
<project ...>
...
<dependencies>
...
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>2.1.4</version>
</dependency>
...
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
...
<dependency> // just for my convinience ;)
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
...
</dependencies>
</project>
With this demo test:
import org.apache.commons.io.IOUtils;
import com.google.common.reflect.ClassPath;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
public class DemoTest {
private static String readAsString(String name) throws IOException {
ClassLoader classloader = DemoTest.class.getClassLoader();
try (InputStream resourceAsStream = classloader.getResourceAsStream(name)) {
if (resourceAsStream == null) {
throw new IOException("resource not found:" + name);
}
StringWriter writer = new StringWriter();
IOUtils.copy(resourceAsStream, writer);
return writer.toString();
}
}
@Test
public void test() throws Exception {
ClassPath.from(getClass().getClassLoader())
.getResources()
.stream()
.filter(e -> e.getResourceName().contains("jquery.min.js"))
.forEach(e-> {
System.out.println("path : " + e);
System.out.println("first bytes: " + readAsString(e.getResourceName()).substring(0,10));
});
}
}
The output is:
path : META-INF/resources/webjars/jquery/2.1.4/jquery.min.js
first bytes: /*! jQuery