read Double Matrix from InputStream - Java java.lang

Java examples for java.lang:Math Matrix

Description

read Double Matrix from InputStream

Demo Code


//package com.java2s;

import java.io.*;
import java.util.*;

public class Main {
    public static double[][] readDoubleMatrix(InputStream stream)
            throws IOException {
        List<List<Double>> listRep = new ArrayList<List<Double>>();

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                stream));/*from ww w.j  a  va2 s.c  o  m*/
        while (reader.ready()) {
            String line = reader.readLine();
            String[] vals = line.trim().split("\\s+");

            List<Double> row = new ArrayList<Double>();
            for (String val : vals) {
                row.add(Double.parseDouble(val));
            }
            listRep.add(row);
        }
        reader.close();

        int rows = listRep.size();
        double[][] arrayRep = new double[listRep.size()][];
        for (int i = 0; i < rows; i++) {
            List<Double> row = listRep.get(i);
            int cols = row.size();
            arrayRep[i] = new double[cols];
            for (int j = 0; j < cols; j++) {
                arrayRep[i][j] = row.get(j);
            }
        }

        return arrayRep;
    }
}

Related Tutorials