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.
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
- Video Downloader
- Steem Blockchain Tools
- Free Cryptos API
- VPS Database
- Computing Technology Blog
- A few useless tools
- And some other online software/tools
- Merge Files/Videos
- LOGO Turtle Programming Chrome Extension
- Teaching Kids Programming - Youtube Channel and All Contents
Delegation Service
Important Update of Delegation Service!
Support me
If you like my work, please:
- Buy Me a Coffee, Thanks!
- Become my Sponsor, Thanks!
- Voting for me:
https://steemit.com/~witnesses type in justyy and click VOTE
- Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
- Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
- 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