The Java Method to Read Content of File into a String


The following FileUtils.readFile takes a file path, and a second paramter charset – then it will read the content of the file and return as a string. This is a handy method similar to file_get_contents in PHP.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class FileUtils {
    public static String readFile(String path, String charSet) {
        var s = new StringBuffer();
        if (charSet == null || charSet.isBlank() || charSet.isEmpty()) {
            charSet = "UTF-8";
        }
        try (var reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), charSet))) {
            var ts = "";
            while ((ts = reader.readLine()) != null) {
                s.append(ts + System.lineSeparator());
            }
            return s.toString();
        } catch (IOException e) {
            System.err.println(e);
        }
        return null;
    }
}
class FileUtils {
    public static String readFile(String path, String charSet) {
        var s = new StringBuffer();
        if (charSet == null || charSet.isBlank() || charSet.isEmpty()) {
            charSet = "UTF-8";
        }
        try (var reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), charSet))) {
            var ts = "";
            while ((ts = reader.readLine()) != null) {
                s.append(ts + System.lineSeparator());
            }
            return s.toString();
        } catch (IOException e) {
            System.err.println(e);
        }
        return null;
    }
}

The charset if left blank or null, will be set to “UTF-8”. The file is opened via FileInputStream, InputStreamReader and BufferedReader. And the content is put into a StringBuffer.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
202 words
Last Post: Teaching Kids Programming - Largest Odd Number in String
Next Post: Teaching Kids Programming - Max Number of Points on a Line

The Permanent URL is: The Java Method to Read Content of File into a String

Leave a Reply