forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReadFile.java
71 lines (62 loc) · 2.49 KB
/
ReadFile.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.rampatra.misc;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Various ways to read a file in Java.
*
* @author rampatra
* @since 2019-06-03
*/
public class ReadFile {
private static Stream<String> readFile(String filePath) throws IOException {
return Files.lines(Paths.get(filePath)); // use Files.readAllLines() to return a List<String> instead of Stream<String>
}
private static String readFile(Path filePath) throws IOException {
Stream<String> lines = Files.lines(filePath);
String data = lines.collect(Collectors.joining("\n"));
lines.close();
return data;
}
private static List<String> readLargeFile(Path filePath) throws IOException {
try (BufferedReader reader = Files.newBufferedReader(filePath)) {
List<String> result = new ArrayList<>();
for (; ; ) {
String line = reader.readLine();
if (line == null)
break;
result.add(line);
}
return result;
}
}
private static String readFileOldWay(String filePath) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
StringBuilder builder = new StringBuilder();
String currentLine = reader.readLine();
while (currentLine != null) {
builder.append(currentLine);
builder.append("\n");
currentLine = reader.readLine();
}
// reader.close(); not required as try-with-resources is used
return builder.toString();
}
}
public static void main(String[] args) throws IOException {
readFile("src/main/java/com/rampatra/misc/reverseandadd.txt").forEach(System.out::println);
System.out.println("==================");
System.out.println(readFile(Paths.get("src/main/java/com/rampatra/misc/reverseandadd.txt")));
System.out.println("==================");
System.out.println(readLargeFile(Paths.get("src/main/java/com/rampatra/misc/reverseandadd.txt")));
System.out.println("==================");
System.out.println(readFileOldWay("src/main/java/com/rampatra/misc/reverseandadd.txt"));
}
}