Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How do I create a Java string from the contents of a file?

I've been utilizing the idiom underneath for quite a while. What's more, it is by all accounts the most far-reaching, in any sites on the locales I've visited.

Is there a superior/diverse approach to add a file to a string in Java?

private String readFile(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");

try {
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}

return stringBuilder.toString();
} finally {
reader.close();
}
}
by

2 Answers

espadacoder11
If you're willing to use an external library, check out Apache Commons IO (200KB JAR). It contains an org.apache.commons.io.FileUtils.readFileToString() method that allows you to read an entire File into a String with one line of code.

Example:

import java.io.;
import java.nio.charset.*;
import org.apache.commons.io.
;

public String readFile() throws IOException {
File file = new File("data.txt");
return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
}
kshitijrana14
A very lean solution based on Scanner:
Scanner scanner = new Scanner( new File("poem.txt") );
String text = scanner.useDelimiter("\\A").next();
scanner.close(); // Put this call in a finally block

Or, if you want to set the charset:
Scanner scanner = new Scanner( new File("poem.txt"), "UTF-8" );
String text = scanner.useDelimiter("\\A").next();
scanner.close(); // Put this call in a finally block

Or, with a try-with-resources block, which will call scanner.close() for you:
try (Scanner scanner = new Scanner( new File("poem.txt"), "UTF-8" )) {
String text = scanner.useDelimiter("\\A").next();
}

Remember that the Scanner constructor can throw an IOException. And don't forget to import java.io and java.util.

Login / Signup to Answer the Question.