Julian Cienfuegos Julian Cienfuegos - 4 months ago 7
Java Question

Reading a CSV in Java / Jython

Here's a simple problem:

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;
}


from jython I import properly, and then call the function as

readPointCloudFile("points.txt", 3)


This gives the error

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

Answer

You never read from the file. You pass the file name to the Scanner and assume that this string is your csv data, but it is just the filename. Reading a file can be done as follows when you use 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;
}