将文本文件读入2d数组JAVA

时间:2016-10-21 19:44:48

标签: java arrays 2d bufferedreader readfile

我正在尝试阅读一个填充了一堆双打的给定文本文件,文本文件看起来像这样(每行之间没有空格):

  

0,0.007133248,0.003747135,0.0034464097,0.009517824,0.0036065334,   0.007921185,0.0041013476

     

1,0.0022223865,5.804103E-4,5.69-27576E-4,0.008850083,0.003269921,   3.7322243E-4,0.0011008179

     

2,0.0051101227,0.008973722,0.0013274436,0.00922496,0.0050817304,   0.004631279,0.0069321943

基本上 1000 8 列,并且我试图将其转换为2d数据数组[1000] [8],我无法迭代数据虽然。到目前为止我所拥有的,任何帮助都将不胜感激!

  public static void readFile2() throws IOException{

    Double[][] data = new Double[1000][8];
    int row = 0;
    int col = 0;
    Scanner scanner = null;
    scanner = new Scanner(new BufferedReader(new FileReader("/Users/Roman/Documents/workspace/cisc124/Logger (1).csv")));

    while (scanner.hasNext() && scanner !=null) {
        scanner.useDelimiter(",");
        while(row<data.length && col<8){
        data[row][col] = Double.parseDouble(scanner.next());
        col++;
        //System.out.print(Arrays.deepToString(data));

    }
    col=0;
    row++;
    }
    System.out.println(Arrays.deepToString(data));
    scanner.close();
}

1 个答案:

答案 0 :(得分:0)

逐行读取文件会更方便..

String[] data = new String[1000];
int row = 0;
try {
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "utf-8"));         

    String line;
    while ((line = br.readLine()) != null) {
        data[row]= line;
        row++;
    }
    br.close();

} catch (IOException e) {
    e.printStackTrace();
}

并在最后做同样的

System.out.println(Arrays.ToString(data));

或者如果您需要给定索引处的元素,则拆分一行并使用Double.parse();