-1

Possible Duplicate:
Java split() method strips empty strings at the end?

we have a requirement like reading a file content and uploading the data to the database. the file content will be separated by delimiter '|' like this

4000|name|state|city|zip||country|||address||

I can also have null values for certain column for which there is no data in between "|". for example '||' between zip and country. my problem is string.split("//",'|') is taking the in between null values and returning array considering null values as an element. But the trailing '||' after address is not being considered. As used in the example above, when i use string.split("//",'|') i shd get an string array element of array size 11 but i get only 10.the last null is not getting retreived. Can anyone help with the solution?

Community
  • 1
  • 1

2 Answers2

4

Just use the regular split(String, int) method inside the String class:

String line = "4000|name|state|city|zip||country|||address||";
String data[] = line.split("\\|", -1); // escaped, because of regular expressions

The minus one is a convention that indicates that the string will be split as you want it.

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
0

Yes to use split is obvious, but you may consider this options too:

Why not just using string.indexOf("|", indexToStartFrom) ? Is a bit of hassle, but works for sure without having to think too much about regex.


Or there is the library OpenCsv http://opencsv.sourceforge.net/ , which is commercial friendly. Apache 2.0 License

keiki
  • 3,260
  • 3
  • 30
  • 38
  • No need to use indexOf since split already has the desired functionality built in. All you have to do is read the documentation or search this site for identical questions (see comments). – jahroy Jul 11 '12 at 20:36