The Java Method to Read Content of File into a String

in programming •  4 months ago 

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.

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.

Reposted to Blog

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

Important Update of Delegation Service!

  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!