Share

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) {
                sb.append(line).append(IChar.NEW_LINE);
            }
            return sb.toString();
        } catch (Exception e) {
            throw new ServiceInitException("Error loading from: " + resourceLocation, e);
        }
    }

1 comment:

  1. You're better off doing something to the affect of:


    FileInputStream fis = new FileInputStream(f);
    byte[] buffer = new byte[f.length()];
    int read = 0;
    while(read > 0){
    read += fis.read(buffer, read, buffer.length - read);
    }
    return new String(buffer);


    You don't really need to read line by line. This will read in the file much faster.

    With that said, it's a lot easier in groovy:


    String s = new File(...).text

    ReplyDelete