文件阅读器返回空

时间:2016-07-20 16:19:35

标签: java file

我有用于读取csv文件的Java代码,但输出为NULL。 代码读取文件并将其分配给双数组。

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

public class CSVReader {
  public static void main(String[] args) throws IOException {
    try {
      double[][] Data = null;
      Data = CSVReader.read("C:\\Users\\mrezz\\Data.csv", true);
      System.out.println(Arrays.deepToString(Data));
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }

  public static double[][] read(String theFile, boolean hasTitle) throws IOException {
    try {
      boolean firstTime = true;
      double[][] data = null;

      File file = new File(theFile);
      int row = 0;
      int col = 0;

      BufferedReader reader = new BufferedReader(new FileReader(file));
      bufferedReader.close();

      String line;

      if (hasTitle) {
        line = reader.readLine();
      }
      while ((line = reader.readLine()) != null) {

        if (firstTime) {
          firstTime = false;

          StringTokenizer st = new StringTokenizer(line, ",");
          col = 0;
          while (st.hasMoreTokens()) {
            st.nextToken();
            col++;
          }
          data = new double[row][col];
          col = 0;
          continue;
        }
        StringTokenizer st = new StringTokenizer(line, ",");
        while (st.hasMoreTokens()) {

          data[row][col] = Double.valueOf(st.nextToken());
          col++;
        }
        col = 0;
        row++;
      }

      return data;

    } catch (Exception e) {
      return null;
    }
  }
}

代码应该将文件分配给(double [] [] data)数组。

任何帮助,请

1 个答案:

答案 0 :(得分:0)

您可能会收到异常并返回null而不向用户报告。

我怀疑上面代码中的最后一个return null;