Read file to string
📝 JavaEasily load the entire contents of a file into a single string variable in Java.
Java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path; public class FileToString { public static void main(String[] args) throws IOException { String content = Files.readString(Path.of("file.txt")); System.out.println(content); }
}
Comments
Yeah, since Java 11 you can just use
Files.readString(path)- super clean, no loops or streams needed. If you're on an older version,new Scanner(file).useDelimiter("\\Z").next()does the trick in one line too.