001: package JSci.io;
002:
003: import java.lang.Double;
004: import java.io.*;
005: import java.util.Vector;
006:
007: import JSci.maths.*;
008:
009: /**
010: * Text reader, reads data text files/streams.
011: * This class uses buffered I/O.
012: * @version 1.7
013: * @author Mark Hale
014: */
015: public final class TextReader extends InputStreamReader {
016: private final BufferedReader reader = new BufferedReader(this );
017:
018: /**
019: * Reads text data from an input stream.
020: */
021: public TextReader(InputStream stream) {
022: super (stream);
023: }
024:
025: /**
026: * Reads a text file with the specified system dependent file name.
027: * @param name the system dependent file name.
028: * @exception FileNotFoundException If the file is not found.
029: */
030: public TextReader(String name) throws FileNotFoundException {
031: super (new FileInputStream(name));
032: }
033:
034: /**
035: * Reads a text file with the specified File object.
036: * @param file the file to be opened for reading.
037: * @exception FileNotFoundException If the file is not found.
038: */
039: public TextReader(File file) throws FileNotFoundException {
040: super (new FileInputStream(file));
041: }
042:
043: /**
044: * Read a single character.
045: * @exception IOException If an I/O error occurs.
046: */
047: public int read() throws IOException {
048: return reader.read();
049: }
050:
051: /**
052: * Reads data to an array.
053: * @exception IOException If an I/O error occurs.
054: */
055: public double[][] readArray() throws IOException {
056: final Vector data = new Vector(10);
057: for (int ch = read(); ch != '\n' && ch != -1;) {
058: if (isNumber(ch)) {
059: StringBuffer str = new StringBuffer();
060: do {
061: str.append((char) ch);
062: ch = read();
063: } while (isNumber(ch));
064: data.addElement(str.toString());
065: }
066: while (!isNumber(ch) && ch != '\n' && ch != -1)
067: ch = read();
068: }
069: int cols = data.size();
070: int rows = 1;
071: for (int ch = read(); ch != -1;) {
072: if (isNumber(ch)) {
073: StringBuffer str = new StringBuffer();
074: do {
075: str.append((char) ch);
076: ch = read();
077: } while (isNumber(ch));
078: data.addElement(str.toString());
079: }
080: while (!isNumber(ch) && ch != '\n' && ch != -1)
081: ch = read();
082: if (ch == '\n') {
083: ch = read();
084: rows++;
085: }
086: }
087: double array[][] = new double[rows][cols];
088: for (int j, i = 0; i < rows; i++) {
089: for (j = 0; j < cols; j++)
090: array[i][j] = Double.parseDouble(data.elementAt(
091: i * cols + j).toString());
092: }
093: return array;
094: }
095:
096: private boolean isNumber(int ch) {
097: return Character.isDigit((char) ch) || ch == '.' || ch == '+'
098: || ch == '-' || ch == 'e' || ch == 'E';
099: }
100: }
|