What is simplest way to read a file into String?

String content = new Scanner(new File("D:\\test.txt")).useDelimiter("\\Z").next();

OR

byte[] bytes = Files.readAllBytes(Paths.get("D:\\test.txt")); String str = new String(bytes, StandardCharsets.UTF_8);

Using Scanner Class

The following Java code will read an entire file into the String.

Example
import java.io.*; import java.util.Scanner; public class TestClass{ public static void main(String[] args) { try{ String content = new Scanner(new File("D:\\test.txt")).useDelimiter("\\Z").next(); System.out.println(content); }catch(Exception e){ System.out.println(e); } } }

Note : useDelimiter("\\Z") is set the delimiter to the end of the file

Java NIO

Java NIO, also known as New IO, is a captivating and advanced IO Application Programming Interface (API) for Java. It revolutionizes data handling by introducing a non-blocking I/O model that enhances efficiency and responsiveness. This API stands out by enabling concurrent handling of multiple connections, facilitating efficient network communication for applications with numerous clients.

By using channels, selectors, and buffers, Java NIO empowers developers to build robust network applications that overcome the limitations of traditional IO. The concept of buffers optimizes data manipulation and enables swift and reliable data processing. Java NIO's comprehensive framework offers fine-grained control over IO operations, supporting asynchronous I/O and customization to meet specific project requirements.

Stream Oriented vs. Buffer Oriented

Java IO follows a stream-oriented approach, the act of reading involves retrieving one or more bytes at a time from a given stream. Subsequently, the responsibility of handling and utilizing these read bytes lies entirely in your hands. Conversely, Java NIO introduces a buffer-oriented approach, which distinguishes itself with slight dissimilarity. With this method, data is first read into a buffer, where it awaits subsequent processing and manipulation.

The following Java code is a compact, robust idiom for Java 7 , wrapped up in a utility method.

Full Source
import java.nio.file.Files; import java.nio.file.Paths; import java.nio.charset.StandardCharsets; public class TestClass{ public static void main(String[] args) { try{ byte[] bytes = Files.readAllBytes(Paths.get("D:\\test.txt")); String str = new String(bytes, StandardCharsets.UTF_8); System.out.println(str); }catch(Exception e){ System.out.println(e); } } }