@@ -0,0 +1,2546 @@
+package com.rampatra.misc;%0A%0Aimport java.io.BufferedReader;%0Aimport java.io.FileReader;%0Aimport java.io.IOException;%0Aimport java.nio.file.Files;%0Aimport java.nio.file.Path;%0Aimport java.nio.file.Paths;%0Aimport java.util.ArrayList;%0Aimport java.util.List;%0Aimport java.util.stream.Collectors;%0Aimport java.util.stream.Stream;%0A%0A%0A/**%0A * Various ways to read a file in Java.%0A *%0A * @author rampatra%0A * @since 2019-06-03%0A */%0Apublic class ReadFile %7B%0A%0A    private static Stream%3CString%3E readFile(String filePath) throws IOException %7B%0A        return Files.lines(Paths.get(filePath)); // use Files.readAllLines() to return a List%3CString%3E instead of Stream%3CString%3E%0A    %7D%0A%0A    private static String readFile(Path filePath) throws IOException %7B%0A        Stream%3CString%3E lines = Files.lines(filePath);%0A        String data = lines.collect(Collectors.joining(%22%5Cn%22));%0A        lines.close();%0A        return data;%0A    %7D%0A%0A    private static List%3CString%3E readLargeFile(Path filePath) throws IOException %7B%0A        try (BufferedReader reader = Files.newBufferedReader(filePath)) %7B%0A            List%3CString%3E result = new ArrayList%3C%3E();%0A            for (; ; ) %7B%0A                String line = reader.readLine();%0A                if (line == null)%0A                    break;%0A                result.add(line);%0A            %7D%0A            return result;%0A        %7D%0A    %7D%0A%0A    private static String readFileOldWay(String filePath) throws IOException %7B%0A        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) %7B%0A            StringBuilder builder = new StringBuilder();%0A            String currentLine = reader.readLine();%0A            while (currentLine != null) %7B%0A                builder.append(currentLine);%0A                builder.append(%22%5Cn%22);%0A                currentLine = reader.readLine();%0A            %7D%0A            // reader.close(); not required as try-with-resources is used%0A%0A            return builder.toString();%0A        %7D%0A    %7D%0A%0A    public static void main(String%5B%5D args) throws IOException %7B%0A        readFile(%22src/main/java/com/rampatra/misc/reverseandadd.txt%22).forEach(System.out::println);%0A        System.out.println(%22==================%22);%0A        System.out.println(readFile(Paths.get(%22src/main/java/com/rampatra/misc/reverseandadd.txt%22)));%0A        System.out.println(%22==================%22);%0A        System.out.println(readLargeFile(Paths.get(%22src/main/java/com/rampatra/misc/reverseandadd.txt%22)));%0A        System.out.println(%22==================%22);%0A        System.out.println(readFileOldWay(%22src/main/java/com/rampatra/misc/reverseandadd.txt%22));%0A    %7D%0A%7D%0A

Read file in Java: done