Reading from a text file and storing in a String

file, file-io, java

Solution

These are the necersary imports:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

And this is a method that will allow you to read from a File by passing it the filename as a parameter like this: `readFile("yourFile.txt");`

String readFile(String fileName) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        return sb.toString();
    } finally {
        br.close();
    }
}

Problem

How can we read data from a text file and store in a String variable? is it possible to pass the filename in a method and it would return the String which is the text from the file. What kind of utilities do I have to import? A list of statements will be great.

Original source

Related problems