在Java / Jython中读取CSV

时间:2016-07-18 20:46:35

标签: java csv jython

这是一个简单的问题:

public static double[] stringsToDoubles(String[] inputArr) {
    double[] nums = new double[inputArr.length];
    for (int i = 0; i < nums.length; i++) {
        nums[i] = Double.parseDouble(inputArr[i]);
    }
    return nums;
}

public static double[][] readPointCloudFile(String filename, int n) {
    double[][] points = new double[n][];
    String delimiter = ",";
    Scanner sc = new Scanner(filename);
    for (int i = 0; i < n; i++) {
        String line = sc.nextLine();
        points[i] = stringsToDoubles(line.split(delimiter));
    }
    return points;
}
从jython

我正确导入,然后将该函数调用为

    readPointCloudFile("points.txt", 3)

这给出了错误

    java.lang.NumberFormatException: java.lang.NumberFormatException: For input string: "points.txt"

2 个答案:

答案 0 :(得分:1)

你永远不会从文件中读取。您将文件名传递给扫描程序并假设此字符串是您的csv数据,但它只是文件名。 使用Java 8时,可以按如下方式读取文件:

import java.nio.file.Files;
import java.nio.file.Paths;
[...]

public static double[][] readPointCloudFile(String filename, int n) {
  double[][] points = new double[n][];
  String delimiter = ",";
  String filecontent = new String(Files.readAllBytes(Paths.get(filename)));
  Scanner sc = new Scanner(filecontent);
  for (int i = 0; i < n; i++) {
      String line = sc.nextLine();
      points[i] = stringsToDoubles(line.split(delimiter));
  }
  return points;
}

答案 1 :(得分:1)

这是我解决自己问题的精神的解决方案,但我会给别人一些信任,因为其他解决方案可能更好。

 public static double[] stringsToDoubles(String[] inputArr){
     double[] nums = new double[inputArr.length];
     for(int i = 0; i < nums.length; i++){
         nums[i] = Double.parseDouble(inputArr[i]);
     }
     return nums;
 }

 public static double[][] readPointCloudFile(String filename, int n) throws FileNotFoundException{
     double[][] points = new double[n][];
     String delimiter = ",";
     try{
         Scanner sc = new Scanner(new File(filename));
         for(int i = 0; i < n; i++){
             String line = sc.nextLine();
             points[i] = stringsToDoubles(line.split(delimiter));
         }
     } catch (FileNotFoundException e){
         System.err.println(e.getMessage());
     } finally {
         return points;
     }
 }