string tokenizer in Java

ASD picture ASD · Mar 1, 2010 · Viewed 97.2k times · Source

I have a text file which contains data seperated by '|'. I need to get each field(seperated by '|') and process it. The text file can be shown as below :

ABC|DEF||FGHT

I am using string tokenizer(JDK 1.4) for getting each field value. Now the problem is, I should get an empty string after DEF.However, I am not getting the empty space between DEF & FGHT.

My result should be - ABC,DEF,"",FGHT but I am getting ABC,DEF,FGHT

Answer

Desintegr picture Desintegr · Mar 1, 2010

From StringTokenizer documentation :

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

The following code should work :

String s = "ABC|DEF||FGHT";
String[] r = s.split("\\|");