1 package org.catacomb.numeric.data;
2
3 import java.io.BufferedReader;
4 import java.io.File;
5 import java.io.FileReader;
6 import java.util.StringTokenizer;
7
8 import org.catacomb.report.E;
9
10 public class AsciiIO {
11
12 public static DataTable readTable(File f) {
13 DataTable ret = null;
14
15 int ncol = 0;
16
17 boolean doneHeadings = false;
18 if (f.exists()) {
19 ret = new DataTable();
20 ret.setID(f.getName());
21
22 try {
23 BufferedReader br = new BufferedReader(new FileReader(f));
24 while (br.ready()) {
25 String line = br.readLine();
26 line = line.trim();
27 if (line.length() > 0) {
28
29 StringTokenizer st = new StringTokenizer(line, " ,;\t");
30 if (ncol == 0) {
31 ncol = st.countTokens();
32 ret.setNColumn(ncol);
33 }
34
35 if (st.countTokens() < ncol) {
36 E.warning("too few elements in row - skipping " + line);
37 } else {
38 if (st.countTokens() > ncol) {
39 E.warning("extra tokens in line beyond " + ncol + "? " + line);
40 }
41
42 if (line.startsWith("#")) {
43 if (!doneHeadings) {
44 st = new StringTokenizer(line, " ,;\t");
45 String[] sa = readStringRow(st, ncol);
46 ret.setHeadings(sa);
47 doneHeadings = true;
48 }
49
50 } else {
51 double[] da = readRow(st, ncol);
52
53 if (da == null) {
54 E.info("Scrapping " + line);
55 } else {
56 ret.addRow(da);
57 }
58 }
59
60 }
61
62 }
63 }
64 } catch (Exception ex) {
65 E.warning("file read exception for " + f + " " + ex);
66 ex.printStackTrace();
67 }
68
69
70 } else {
71 E.warning("no such file " + f);
72 }
73 if (ret != null) {
74 ret.close();
75 }
76 return ret;
77 }
78
79
80
81
82 public static double[] readRow(StringTokenizer st, int ncol) {
83 double[] ret = new double[ncol];
84 try {
85 for (int i = 0; i < ret.length; i++) {
86 ret[i] = Double.parseDouble(st.nextToken());
87 }
88 } catch (Exception ex) {
89 ret = null;
90 }
91 return ret;
92 }
93
94
95
96 public static String[] readStringRow(StringTokenizer st, int ncol) {
97 String[] ret = new String[ncol];
98 if (st.countTokens() < ncol) {
99 E.error("need " + ncol + " but got only " + st.countTokens() + " tokens in " + st);
100 } else {
101 for (int i = 0; i < ncol; i++) {
102 ret[i] = st.nextToken();
103 }
104 }
105 return ret;
106 }
107
108
109
110
111 public static double[] readRow(String line) {
112 StringTokenizer st = new StringTokenizer(line, " ,;\t[]");
113 int nc = st.countTokens();
114 return readRow(st, nc);
115 }
116
117 }