blob: fa588efb79aee1da1f544a915b84f7d9b9bcb562 (
plain)
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
|
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Arrays;
/*
* @author
* Kian Agheli
*
* References:
*
* Date:
* 2024-05-08
*
* Purpose of class:
* Read from and interpret CSV files.
*/
public class CSVReader extends Reader {
String[] header; // A CSV file has-a header. One line, multiple fields.
/* Array of Hash map from header to value for each
line past the header. */
ArrayList<HashMap<String,String>> body; // A CSV file has-a body. Multiple lines, multiple fields.
public CSVReader(File file) {
super(file); // Call parent constructor
body = new ArrayList<HashMap<String,String>>();
parse();
}
/**
* Parse CSV file.
*/
public void parse() {
String[] lines = this.getContents().split("\n");
this.header = lines[0].split(",");
/* Iterate over all lines of the body. */
for (int i = 1; i < lines.length; i++) {
String[] fields = lines[i].split(",");
HashMap<String,String> map = new HashMap<String,String>();
/* For each of the columns, add the associated
value in this row. */
for (int j = 0; j < header.length; j++) {
map.put(header[j], fields[j]);
}
body.add(map);
}
}
public int getLength() {
return body.size();
}
public String get(int i, String key) {
return body.get(i).get(key);
}
}
|