Getting field from a Tab delimiter txt file.
Hi Hope you can help
I have successfully uploaded a tab delimited txt file and got the first line into a String using BufferedReader.readLine.
I have 6 field in this string seperated by tabs.
if there a quick way of getting these field out of the string?
thanks in advance
When reading each line of a CSV file with BufferedReader, the simplest way to extract all the fields for the line is to use a StringTokenizor which splits the line into a collection of values depending on the delimiter specified (For CSV this would obviously be the a comma) which can then be looped over and processed. The follwing shows how to read in the file and extract the fields from each line.
File file = new File("something.csv");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
//read each line of text file
while((line = reader.readLine()) != null)
{
StringTokenizer st = new StringTokenizer(line,",");
while (st.hasMoreTokens())
{
//get next token
String field = st.nextToken();
//do something with the field...
}
}
//close the file
reader.close();
This method however has its drawbacks as it cannot cope with empty fields (i.e. a line that has field , , field will miss out the empty field) and so you could use String.split(regular expression) instead of a StringTokenizor as follows:
File file = new File("something.csv");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
//read each line of text file
while((line = reader.readLine()) != null)
{
String[] fields = line.split("\\,");
for (int i = 0, i < fields.length(), i++)
{
//get next field
String field = fields[i];
//do something with the field...
}
}
//close the file
reader.close();
However this too has its drawbacks as a field that contains a comma will be split into two fields (the StringTokenizor will also do this).Also String.split is only available n JRE 1.4. Therefore for a full implementation of CSV file handling I would suggest looking at a specific API such as the one at the following address, it depends how robust a solution you are after. This API provides a parsing object to parse the file into a two dimensional String array to then process, and a printing object to output data.
http://ostermiller.org/utils/CSV.html