Reputation: 430
I'm trying to read from this CSV file that looks like
"1.23","2.45","3.25"
"4","5","6"
"7","8","9"
"10","11","12"
Now the problem is that while Java can find my file, line split isn't returning what I'm expecting.
Here is my attempt at reading from the csv file.
File root = new File(Thread.currentThread().getContextClassLoader().getResource("").toURI());
File resource = new File(root, "coords.csv");
float[] x = new float[5000];
float[] y = new float[5000];
float[] z = new float[5000];
int coordIndex = 0;
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
/* 1, 2, 3,
* 3, 5, 6,
*/
try{
System.out.println(coordIndex);
br = new BufferedReader(new FileReader(resource));
String[] coordinates = line.split(cvsSplitBy);
/*I get an error from accessing an array out of bounds */
System.out.println(coordinates[0]);
System.out.println(coordinates[1]);
System.out.println(coordinates[2]);
x[coordIndex] = Float.parseFloat(coordinates[0]);
y[coordIndex] = Float.parseFloat(coordinates[1]);
z[coordIndex] = Float.parseFloat(coordinates[2]);
coordIndex++;
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is my output error:
IOException: java.lang.ArrayIndexOutOfBoundsException: 1
Any ideas??
Upvotes: 0
Views: 2199
Reputation: 36349
Your line
you are splitting is the empty line. This results in split
returning an empty array.
The error you get is typical for non-defensive programming: the result of split() depends entirely on user input (that you do not know ex ante), hence it is a must to check the result:
coords = line.split(",");
if (coords.length == 3) {
// looks good
}
else {
System.err.println("Bad data: " + line);
}
Upvotes: 0
Reputation: 44448
String line = "";
br = new BufferedReader(new FileReader(resource));
String[] coordinates = line.split(cvsSplitBy);
You never have data in your line
.
You have to add a loop to read everything:
while(line = br.readLine() != null) { }
Upvotes: 1