forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCsvs.java
More file actions
62 lines (49 loc) · 1.86 KB
/
Csvs.java
File metadata and controls
62 lines (49 loc) · 1.86 KB
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
package modern.challenge;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
public final class Csvs {
private Csvs() {
throw new AssertionError("Cannot be instantiated");
}
public static List<List<String>> readAsObject(
Path path, Charset cs, String delimiter) throws IOException {
if (path == null || delimiter == null) {
throw new IllegalArgumentException("Path/delimiter cannot be null");
}
cs = Objects.requireNonNullElse(cs, StandardCharsets.UTF_8);
List<List<String>> content = new ArrayList<>();
try (BufferedReader br = Files.newBufferedReader(path, cs)) {
String line;
while ((line = br.readLine()) != null) {
String[] values = line.split(Pattern.quote(delimiter));
content.add(Arrays.asList(values));
}
}
return content;
}
public static List<Melon> readAsMelon(
Path path, Charset cs, String delimiter) throws IOException {
if (path == null || delimiter == null) {
throw new IllegalArgumentException("Path/delimiter cannot be null");
}
cs = Objects.requireNonNullElse(cs, StandardCharsets.UTF_8);
List<Melon> content = new ArrayList<>();
try (BufferedReader br = Files.newBufferedReader(path, cs)) {
String line;
while ((line = br.readLine()) != null) {
String[] values = line.split(delimiter);
content.add(new Melon(values[0], Integer.valueOf(values[1])));
}
}
return content;
}
}