Reputation: 49
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.
Upvotes: 2
Views: 6152
Reputation: 18459
Try using more tested code like http://opencsv.sourceforge.net/ for parsing CSV files.
Upvotes: 1
Reputation: 420971
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
Upvotes: 0
Reputation: 199
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#
Upvotes: 0