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.
–EOF (The Ultimate Computing & Technology Blog) —
185 wordsLast Post: Teaching Kids Programming - Largest Odd Number in String
Next Post: Teaching Kids Programming - Max Number of Points on a Line