From ada80f74d26a632c1d6960f04f773f4fe51fc10d Mon Sep 17 00:00:00 2001 From: ArghKevin Date: Wed, 8 May 2024 00:07:12 -0700 Subject: Basic CSV parsing. --- src/CSVReader.java | 38 +++++++++++++++++++++++++++++++++++++- src/ComparisonView.java | 3 ++- src/Reader.java | 2 ++ 3 files changed, 41 insertions(+), 2 deletions(-) (limited to 'src') 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> body; // A CSV file has-a body. Multiple lines, multiple fields. public CSVReader(File file) { super(file); // Call parent constructor + body = new ArrayList>(); + 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 map = new HashMap(); + /* 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 map : body) { + for (int i = 0; i < header.length; i++) { + System.out.printf("%s\t", map.get(header[i])); + } + System.out.println(); + } } } diff --git a/src/ComparisonView.java b/src/ComparisonView.java index ca5929e..631c718 100644 --- a/src/ComparisonView.java +++ b/src/ComparisonView.java @@ -66,7 +66,7 @@ public class ComparisonView extends JFrame { ArrayList metadataList = new ArrayList(); /* Enhanced for loop. */ for (File file : fileList) { - if (file.getPath().endsWith("METADATA.pb")) { + if (file.getPath().endsWith(".pb")) { metadataList.add(file); } } @@ -80,5 +80,6 @@ public class ComparisonView extends JFrame { public static void main(String[] argv) { new ComparisonView(); + new CSVReader(new File("families.csv")); } } diff --git a/src/Reader.java b/src/Reader.java index 934bf5f..80e795d 100644 --- a/src/Reader.java +++ b/src/Reader.java @@ -26,8 +26,10 @@ class Reader { /* Scan over the contents of the input file. */ scan = new Scanner(file); /* Save to object. */ + contents = scan.nextLine() + "\n"; while (scan.hasNextLine()) { contents += scan.nextLine(); + contents += "\n"; } /* On exception, exit. */ } catch (Exception e) { -- cgit v1.2.3