summaryrefslogtreecommitdiff
path: root/src/CSVReader.java
blob: e4af4df581a25eecf2ed6a596ae6118a94be8ca4 (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
59
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Arrays;

/*
 * @author
 * Kian Agheli
 * 
 * References:
 * 
 * Date:
 * 2024-04-28
 * 
 * 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();
	}

	public void parse() {
		String[] lines = this.getContents().split("\n");
		this.header = lines[0].split(",");
		System.out.printf("%d\n", header.length);

		/* 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);
		}

		for (String head : this.header) {
			System.out.printf("%s\t", head);
		}
		System.out.println();
		for (HashMap<String,String> map : body) {
			for (int i = 0; i < header.length; i++) {
				System.out.printf("%s\t", map.get(header[i]));
			}
			System.out.println();
		}
	}
}