开发者

Read one column if some fields are empty in csv file using java

开发者 https://www.devze.com 2023-01-21 05:45 出处:网络
For Example- aa0124 bb029 ac03b8712 zy 开发者_StackOverflow社区ab8143 I want column number 5. As csv file has string tokenizer seperated by \",\". There may have some fields empty which not cou

For Example-

a   a       0           12      4

b   b   0           29

a   c   0   3   b   87      12

z   y 开发者_StackOverflow社区  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.


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


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#


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
0

精彩评论

暂无评论...
验证码 换一张
取 消