What is simplest way to read a file into String?
To read a file into a String
in Java, you can use the readAllBytes()
method of the Files
class and the new String()
constructor:
Path path = Paths.get("file.txt");
String content = new String(Files.readAllBytes(path));
In this example, the readAllBytes()
method reads the content of the file into a byte array and the new String()
constructor creates a new String
object by decoding the byte array using the platform's default charset.
Alternatively, you can use the readAllLines()
method of the Files
class and the join()
method of the String
class:
Path path = Paths.get("file.txt");
List<String> lines = Files.readAllLines(path);
String content = String.join("\n", lines);
In this example, the readAllLines()
method reads the lines of the file into a List
and the join()
method combines the lines into a single String
separated by a newline character.
I hope this helps! Let me know if you have any questions.