What's the best way to have a stringTokenizer split a string of text into predefined variables

I'm not sure if the title is very clear, but basically what I need to do is read a line of text from a file and split into 8 different string variables. Each line will have the same 8 pieces in the same order (title, author, price, etc.). So for each line of text, I want to end up with 8 lines.

The first problem is that the last two fields in the string may or may not be present, so I need to do something with stringTokenizer.hasMoreTokens, otherwise it will randomly die when fields 7 and 8 are not present.

Ideally I would like to do it in one while loop, but I am not sure how to tell this loop that the order of the fields will be such that it can fill all 8 (or 6) lines correctly.Please tell me the best way to use 8 nested if statements!

EDIT: The String.split solution seems to be a part of it, so I'll use that instead of stringTokenizer. However, I'm still not sure what is the best way to feed the individual lines in the constructor. It would be better if the class expected an array and then just did something like this in the constructor:

line[1] = isbn;
line[2] = title;

      

+2


source to share


4 answers


The best way is not to use StringTokenizer at all, but use the String split method . It returns an array of strings and you can get the length from that.

For each line in your file, you can do the following:



String[] tokens = line.split("#");

      

tokens

will now have 6-8 lines. Use tokens.length()

to find out how much and then create your object from the array.

+3


source


Regular expression is the way to go. You can convert input string to String array using split method



http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)

+2


source


Would a regex with capture groups work for you? You can make parts of the expression optional.

An example line of data or three might be helpful.

+1


source


Is it a CSV or similar file? If so, there are libraries to help you, like Apache Commons CSV (link to alternatives on their page too). This will give you a [] line for every line in the file. Just check the size of the array to see what additional fields are present.

0


source







All Articles