August 8, 2010

Java: Read a text file into a String

For some reason this is not easy in java, but lots of time you need to read a text file and i always have to google how to do it... this is my until class to do so.

Note: This uses the Spring ResourceUtils class.

     * @param resourceLocation
     * @return the content of the resource as String
     * @throws ServiceInitException
    public static String getFileAsString(String resourceLocation) throws ServiceInitException {
        try {
            StringBuilder sb = new StringBuilder();
            File file = ResourceUtils.getFile(resourceLocation);
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file));
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
            return sb.toString();
        } catch (Exception e) {
            throw new ServiceInitException("Error loading from: " + resourceLocation, e);