1

I am trying to read a csv file and copy it's data into an array. I can't seem to get it to work this way and I'm not sure why.

String[] row = new String[0];
ArrayList<String[]> csv = new ArrayList<>();

String parser = "SPImages";
CSVReader reader = new CSVReader(new FileReader("C://data.csv"));
String[] nextLine;


while ((nextLine = reader.readNext()) != null){
    System.arraycopy(nextLine, 0, row, 0, nextLine.length);
}
5
  • 2
    Well how large is row? In fact, what's its type? Commented Jan 30, 2013 at 21:38
  • I updated my question with the code where I create row Commented Jan 30, 2013 at 21:43
  • row must have at least the size of the nextLine.length! Commented Jan 30, 2013 at 21:44
  • @MrSmith42 Ignore that part. It was a comment for something else I was trying to do. I just forgot to delete it. I will now. Commented Jan 30, 2013 at 21:47
  • @Aaron Lemon: but even when row is big enough for the arraycopy, you will overwrite the content with each loop iteration. Commented Jan 30, 2013 at 21:48

1 Answer 1

3

Most likely the destination array (in this case "row") is not as big as the source array (in this case "nextLine"). Arrays, unlike Lists, don't auto-resize.

Sign up to request clarification or add additional context in comments.

6 Comments

So I should create row after finding the size of nextLine, huh?
Exactly, your row must be of proper size, as described here: docs.oracle.com/javase/1.5.0/docs/api/java/lang/…
Yes, now that the source code has been updated to include the declaration of row, this is the problem. You will need to create "row" anew each time in the loop, or else you will just be copying over your data each time.
@Aaron Lemon: or better define it big enough from the beginning.
I think he has to create a new instance of row each time through the loop, right? Assuming "row" will be appended to the "csv" variable. If there's just one declaration of "row", that same memory will be overwritten with each line.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.