-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathJavaFileIOExample.java
49 lines (41 loc) · 1.45 KB
/
JavaFileIOExample.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
package IO_example;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class JavaFileIOExample {
public static void main(String... args) throws IOException {
System.out.println("Program started.");
readFileOnDisk("src/test/resources/sample_input.txt");
findUniqueCityNames();
System.out.println("Program finished.");
}
public static void readFileOnDisk(String filePath) throws IOException {
Scanner scanner = new Scanner(new File(filePath));
scanner.useDelimiter(" ");
assertTrue(scanner.hasNext());
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
scanner.close();
}
private static void findUniqueCityNames() throws IOException {
String file = "src/test/resources/city_names.csv";
Scanner scanner = new Scanner(new File(file));
scanner.useDelimiter(",");
Map<String, Integer> map = new HashMap<>();
while (scanner.hasNext()) {
String city = scanner.next();
map.put(city, map.getOrDefault(city, 0) + 1);
}
scanner.close();
System.out.println("Unique city names are: ");
for (String city : map.keySet()) {
if (map.get(city) == 1) {
System.out.println(city);
}
}
}
}