2

For Example-

a   a       0           12      4

b   b   0           29

a   c   0   3   b   87      12

z   y   ab  81      43

I want column number 5.

As csv file has string tokenizer seperated by ",". There may have some fields empty which not counted as tokens.So I did not get fields at same column with same token number.

2
  • Question is not clear. Can you explain a bit more? Commented Oct 21, 2010 at 6:42
  • Could you post a snippet of your csv file? What part of the parsing process are you having trouble with? (for example, can you open the file? can you read it line-by-line?) Commented Oct 21, 2010 at 22:54

3 Answers 3

1

Try using more tested code like http://opencsv.sourceforge.net/ for parsing CSV files.

Sign up to request clarification or add additional context in comments.

Comments

0

Working on a whole lot of assumptions. For each line you should be doing:

String myString;
String[] stringArray = testString.split(",");//To give us a nice indexable format

if(stringArray.length > 6) //Stops us from indexing out of bounds
{
      myString = stringArray[5]; //Because we want the 5th column
}

I've assumed you are looking for column number 5, not the 5th column from the left, as this would be column index 4. (As arrays are 0-based)

I'm not a Java programmer anymore, so please excuse me if any of this is wrong. This would work in c#

Comments

0

It seems your data is tab-separated. In that case the following code should do:

import java.io.*;
import java.util.*;

class Main {
    public static void main(String... args) throws FileNotFoundException {

        Scanner s = new Scanner(new File("data.txt"));
        while (s.hasNextLine()) {
            String line = s.nextLine();
            String[] cols = line.split("\t");
            System.out.println(cols[5]);
            //System.out.println(Arrays.toString(cols));
        }
    }
}

If data contains the following (tab-separated) lines

a   a   0           12  4
b   b   0           29  
a   c   0   3   b   87  12
z   y   ab  81      43  

You'll get the following output from the above program:

12
29
87
43

4 Comments

You are far too nice... I hope this isn't a homework question!
No. But my CSV file is comma seperated.And its not counting empty fields.
well make that clear in the example in your question, and split on "," instead of "\t"...
There may have some empty fields which are not counted as tokens.So I did not get fields at same column with same token number.(Using String tokenizer for getting tokens)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.