zabware zabware - 1 month ago 12
Java Question

How to get file content in java?

to get the content of a txt file I usually use a scanner and iterate over each line to get the content:

Scanner sc = new Scanner(new File("file.txt"));
while(sc.hasNextLine()){
String str = sc.nextLine();
}


Does the java api provide a way to get the content with one line of code like:

String content = FileUtils.readFileToString(new File("file.txt"))

Answer

With Java 7 there is an API along those lines.

Files.readAllLines(Path path, Charset cs)