forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountryService.java
More file actions
63 lines (48 loc) · 1.87 KB
/
CountryService.java
File metadata and controls
63 lines (48 loc) · 1.87 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
63
package com.zetcode.service;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import com.zetcode.bean.Country;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
public class CountryService {
public static Optional<List<Country>> getListOfCountries() throws IOException {
List<Country> countries;
try (InputStream is = CountryService.class.getClassLoader()
.getResourceAsStream("countries.csv")) {
if (is == null) {
return Optional.empty();
}
HeaderColumnNameMappingStrategy<Country> strategy
= new HeaderColumnNameMappingStrategy<>();
strategy.setType(Country.class);
try (var br = new BufferedReader(
new InputStreamReader(is, StandardCharsets.UTF_8))) {
CsvToBean<Country> csvToBean = new CsvToBeanBuilder<Country>(br)
.withType(Country.class)
.withMappingStrategy(strategy)
.withIgnoreLeadingWhiteSpace(true)
.build();
countries = csvToBean.parse();
}
// try (CSVReader reader = new CSVReader(new InputStreamReader(is))) {
//
// String[] nextLine;
// reader.readNext();
//
// while ((nextLine = reader.readNext()) != null) {
//
// var newCountry = new Country(nextLine[0],
// Integer.parseInt(nextLine[1]));
// countries.add(newCountry);
// }
// }
}
return Optional.of(countries);
}
}