In Java 8, you can use the Files.readAllBytes() method to read the entire contents of a file as a byte array, and then convert it to a string using the new String() constructor.
Here’s an example code that demonstrates how to read a complete file without using a loop:
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class ReadFileExample { public static void main(String[] args) { String fileName = "example.txt"; try { byte[] bytes = Files.readAllBytes(Paths.get(fileName)); String content = new String(bytes); System.out.println(content); } catch (IOException e) { e.printStackTrace(); } } }
In this example, we use the Files.readAllBytes() method to read the entire contents of the file as a byte array. Then, we create a new string object by passing the byte array to the String() constructor. Finally, we print the contents of the file to the console.
Approach2:
List<String> lines = Files.readAllLines(Paths.get("file"), StandardCharsets.UTF_8);