Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java StringTokenizer.nextToken() skips over empty fields

I am using a tab (/t) as delimiter and I know there are some empty fields in my data e.g.:

one->two->->three

Where -> equals the tab. As you can see an empty field is still correctly surrounded by tabs. Data is collected using a loop :

 while ((strLine = br.readLine()) != null) {
    StringTokenizer st = new StringTokenizer(strLine, "\t");
    String test = st.nextToken();
    ...
    }

Yet Java ignores this "empty string" and skips the field.

Is there a way to circumvent this behaviour and force java to read in empty fields anyway?

like image 633
FireFox Avatar asked Jul 10 '12 08:07

FireFox


People also ask

Is StringTokenizer deprecated in Java?

StringTokenizer is a legacy class (i.e. there is a better replacement out there), but it's not deprecated.

What does StringTokenizer do in Java?

The string tokenizer class allows an application to break a string into tokens. The tokenization method is much simpler than the one used by the StreamTokenizer class. The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted strings, nor do they recognize and skip comments.

What happens if no delimiter is specified in the StringTokenizer constructor?

Constructors of the StringTokenizer Class It creates StringTokenizer with specified string and delimiter. It creates StringTokenizer with specified string, delimiter and returnValue. If return value is true, delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate tokens.


2 Answers

There is a RFE in the Sun's bug database about this StringTokenizer issue with a status Will not fix.

The evaluation of this RFE states, I quote:

With the addition of the java.util.regex package in 1.4.0, we have basically obsoleted the need for StringTokenizer. We won't remove the class for compatibility reasons. But regex gives you simply what you need.

And then suggests using String#split(String) method.

like image 168
npe Avatar answered Sep 28 '22 20:09

npe


Thank you at all. Due to the first comment I was able to find a solution: Yes you are right, thank you for your reference:

 Scanner s = new Scanner(new File("data.txt"));
 while (s.hasNextLine()) {
      String line = s.nextLine();
      String[] items= line.split("\t", -1);
      System.out.println(items[5]);
      //System.out.println(Arrays.toString(cols));
 }
like image 27
FireFox Avatar answered Sep 28 '22 22:09

FireFox