Reading files from the classpath is a fairly common use case. Configuration files, HTML templates, CSV files and many more are all common use cases. This has always been a bit convoluted. The Java8 Paths
and Files
APIs made this a little simpler. Guava also has a few helper classes that make this very easy to accomplish.
Read Resource as String
Simple helper to load any resource on the classpath and convert it to a String
. Here we are lazy and re-throw IOException
's as unchecked exceptions.
Here it is in action using a JUnit test.
Read Resource as BufferedReader
Simple helper to load any resource on the classpath and convert it to a BufferedReader
. BufferedReader
's are much better for large files. Ideally you won't have very large files included in your JAR and they will be loaded externally so this might not be extremely useful.
Here it is in action using a JUnit test.