1

Background: I'm trying to read from a csv file that I made with excel.

An example line of something I'm trying to read would be

Text,435,435,,,,,,,,,,,,,20,,,,,,,,,,,,,,,,,,,

My code is

BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
ArrayList<Item> itemList = new ArrayList<Item>();

try {
    br = new BufferedReader(new FileReader("/Items.csv"));
    br.readLine();
    while ((line = br.readLine()) != null) {

        // use comma as separator
        String[] stats = line.split(cvsSplitBy);

        for(int i =0; i<stats.length; i++){
            System.out.print(i + ",");
            System.out.print(stats[i] + "," + \n);
        }

This gives an output of my String[]. However this gives an output of

0,Text,1,435,2,435,3,,4,,5,,6,,7,,8,,9,,10,,11,,12,,13,,14,,15,20,

An input of

Text,435,435,,,,,,,,,,1800,,,,,,,,,,,,,,,,,,,,,,

Gives:

0,Amplifying Tome,1,435,2,435,3,,4,,5,,6,,7,,8,,9,,10,,11,1800,

Why is my array stopping at the first number it finds?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
user12092
  • 39
  • 5
  • Are you sure you want split, and not something like [openCSV](http://stackoverflow.com/questions/101100/csv-api-for-java) or [StringTokenizer](http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html)? –  Dec 16 '13 at 02:51
  • Is every number separated by just one `,`? – Paul Samsotha Dec 16 '13 at 02:56
  • 1
    What output do you want? Please clarify your question – Paul Samsotha Dec 16 '13 at 02:58

2 Answers2

0

According to String.split(String) javadoc "trailing empty strings are not included in the resulting array".

If you know how many columns there are exactly, you can use the String.split(String, int) method, with a positive number.

rslemos
  • 2,454
  • 22
  • 32
0

If you have multiple ,s separating the numbers, you need to set the delimiter to one or more. Try :

String[] stats = line.split("[,]+"); <-- signifies one or more comma

Without using the +, what's happening is it is reading a single , as a delimiter, then the next , will be added to the array as String, then the next , is a delimiter, next , a String, next , a delimiter, next , a String and so on.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720