2

I have to read inputs from a file which consists of pipe delimetered strings

A|UK|2|1
B||3|1

StringTokenizer st = new StringTokenizer(data,"|");

String id=st.nextToken();
String country=st.nextToken();
String count=st.nextToken();
String flag=st.nextToken();

for the second line of file,There is a empty content,i want to assign "" string if there is no content,how do i do this using nextToken?

Thank you

Bernad Ali
  • 1,699
  • 6
  • 23
  • 29

2 Answers2

4

I would suggest you to use split and it will work without any exceptions

String yourstring = "B||3|1";
String [] arr = yourstring.split("\\|");

String id=arr[0];
String country=arr[1];
String count=arr[2];
String flag=arr[3];
someone
  • 6,577
  • 7
  • 37
  • 60
3

One solution could be using the three parameter constructor

StringTokenizer(String str, String delim, boolean returnDelims)

passing true as the third parameter. This way StringTokenizer gives you the delimiters as tokens, so you can check empty fields just checking two or more consecutive delimiters.

remigio
  • 4,101
  • 1
  • 26
  • 28