summaryrefslogtreecommitdiff
path: root/src/CSVReader.java
diff options
context:
space:
mode:
authorArghKevin <kagheli@student.sdccd.edu>2024-05-08 00:07:12 -0700
committerArghKevin <kagheli@student.sdccd.edu>2024-05-08 00:07:12 -0700
commitada80f74d26a632c1d6960f04f773f4fe51fc10d (patch)
tree8e68c1b5f35d5c14bb9093fa4f792329361d3995 /src/CSVReader.java
parent9ac10f4ae9ab23f030084b766610741c2e9c1c0c (diff)
Basic CSV parsing.
Diffstat (limited to 'src/CSVReader.java')
-rw-r--r--src/CSVReader.java38
1 files changed, 37 insertions, 1 deletions
diff --git a/src/CSVReader.java b/src/CSVReader.java
index 42b6899..e4af4df 100644
--- a/src/CSVReader.java
+++ b/src/CSVReader.java
@@ -1,4 +1,7 @@
import java.io.*;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Arrays;
/*
* @author
@@ -15,9 +18,42 @@ import java.io.*;
public class CSVReader extends Reader {
String[] header; // A CSV file has-a header. One line, multiple fields.
- String[][] body; // A CSV file has-a body. Multiple lines, 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();
+ }
}
}