Java : Reading file contents into String

This page last changed on Jan 29, 2016 by admin.

About three times a year I have to accomplish the seemingly easy task of reading the contents of a file into a String. Apparently the Sun folks did not find it necessary to create an API for this. So this piece of obscure code is the best I can come up with. There should be a more elegant way to do this.

private String readFile(String fileName) {

    File file = new File(fileName);

    char[] buffer = null;

    try {
        BufferedReader bufferedReader = new BufferedReader(
                new FileReader(file));

        buffer = new char[(int)file.length()];

        int i = 0;
        int c = bufferedReader.read();

        while (c != -1) {
            buffer[i++] = (char)c;
            c = bufferedReader.read();
        }
    } catch (FileNotFoundException e) {
        log.error(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage());
    }

    return new String(buffer);
}

Apache Commons IOUtils makes the job a breeze:

public String readFile(String fileName) throws IOException {

    StringWriter stringWriter = new StringWriter();
    IOUtils.copy(new FileInputStream(new File(fileName)), stringWriter);

    return stringWriter.toString();
}

Java NIO (as of Java 7) is currently the best solution: pure Java, not depending on any external library

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public String readFile(String fileName) throws IOException {
    return new String(Files.readAllBytes(Paths.get(fileName)));
}