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

124 lines
2.7 KiB
Java

package org.hwo.csv;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
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) {
return getColumn(column,0,this.rows.size());
}
public Object[] getColumn(int column,int start) {
return getColumn(column,start,this.rows.size());
}
public Object[] getColumn(int column,int start,int end) {
ArrayList<Object> ret = new ArrayList<>();
for (int n = start; n < end; n++) {
ret.add(this.rows.get(n).getValue(column));
}
return ret.toArray();
}
public <T> T[] getColumn(T[] targetType,int column) {
return getColumn(targetType, column, 0, this.rows.size());
}
public <T> T[] getColumn(T[] targetType,int column,int start) {
return getColumn(targetType, column, start, this.rows.size());
}
@SuppressWarnings("unchecked")
public <T> T[] getColumn(T[] targetType,int column,int start,int end) {
T[] targetArray = (T[])Array.newInstance(targetType.getClass().getComponentType(), end - start);
for (int n = start; n < end; n++) {
Object o = this.rows.get(n).getValue(column);
if (o != null) {
targetArray[n - start] = (T)o;
} else {
targetArray[n - start] = null;
}
}
return targetArray;
}
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() {
StringBuilder csv = new StringBuilder();
for(CSVTableRow r : this.rows) {
csv.append(r.getCSV());
}
return csv.toString();
}
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.equals("")) {
row.addValue(null);
} else 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;
}
}