java-org.hwo/src/org/hwo/csv/CSVTable.java

88 lines
1.6 KiB
Java

package org.hwo.csv;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CSVTable {
ArrayList<CSVTableRow> rows;
public CSVTable() {
this.rows = new ArrayList<>();
}
public void addRow(CSVTableRow row) {
this.rows.add(row);
}
public CSVTableRow getRow(int index) {
return this.rows.get(index);
}
public int getRowCount() {
return this.rows.size();
}
public Object[] getColumn(int column) {
ArrayList<Object> ret = new ArrayList<>();
for(CSVTableRow r : this.rows) {
ret.add(r.getValue(column));
}
return ret.toArray();
}
public int getColumnCount() {
int count = 0;
for(CSVTableRow r : this.rows) {
int rc = r.getColumnCount();
count = rc > count? rc : count;
}
return count;
}
public String getCSV() {
String csv = new String();
for(CSVTableRow r : this.rows) {
csv += r.getCSV();
}
return csv;
}
public static CSVTable ParseCSV(String path) {
CSVTable ret = new CSVTable();
File f = new File(path);
List<String> str = null;
try {
str = Files.readAllLines(f.toPath());
} catch (IOException e) {
e.printStackTrace();
}
if(str == null) {
return null;
}
for(String s : str) {
//parse line
CSVTableRow row = new CSVTableRow();
String[] tokens = s.split(",");
for(String t : tokens) {
if(t.contains("\"")) {
row.addValue(t.substring(1,t.length() - 1));
}
else if(t.contains(".")) {
row.addValue(Float.parseFloat(t));
}
else {
row.addValue(Integer.parseInt(t));
}
}
ret.addRow(row);
}
return ret;
}
}