Skip to content

Instantly share code, notes, and snippets.

@j-tim
Created March 2, 2021 15:25
Show Gist options
  • Save j-tim/18ff2d019d678a159a47c7e17409175e to your computer and use it in GitHub Desktop.
Save j-tim/18ff2d019d678a159a47c7e17409175e to your computer and use it in GitHub Desktop.
Utility to read class path resources as String. Required dependency is on spring-core.
package nl.jtim.utils.resources;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;
import java.io.IOException;
import java.io.InputStream;
public class ClassPathResourceUtils {
private static final String DEFAULT_ENCODING = "utf-8";
private ClassPathResourceUtils() {
}
/**
* Obtains the classpath resource as a {@link String}.
*
* @param classPathResourceLocation location of the file on the classpath
* @return the file content as a UTF encoded String
* @throws RuntimeException in case of an error
*/
public static String readClassPathResourceAsString(String classPathResourceLocation) {
try {
InputStream inputStream = new ClassPathResource(classPathResourceLocation).getInputStream();
return new String(FileCopyUtils.copyToByteArray(inputStream), DEFAULT_ENCODING);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment