Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

extract data column-wise from text file using Java

I'm working under Java and want to extract data according to column from a text file.
"myfile.txt" contents:

    ID     SALARY RANK  
    065    12000   1
    023    15000   2
    035    25000   3
    076    40000   4

I want to extract the data individually according to any Column i.e ID, SALARY, RANK etc
Basically I want to perform operations on individual data according to columns.

I've listed the data from "myfile.txt" by using while loop and reading line-by-line:

    while((line = b.readLine()) != null) {
          stringBuff.append(line + "
");
       }

link: Reading selective column data from a text file into a list in Java

Under bove link it is written to use the following: String[] columns = line.split(" ");

But how to use it correctly, please any hint or help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a regex to detect longer spaces, example:

String text = "ID     SALARY RANK
" +  
            "065    12000   1
" +
            "023    15000   2
" +
            "035    25000   3
" +
            "076    40000   4
";

Scanner scanner = new Scanner(text);

//reading the first line, always have header
//I suppose
String nextLine = scanner.nextLine();
//regex to break on any ammount of spaces
String regex = "(\s)+";


String[] header = nextLine.split(regex);

//this is printing all columns, you can 
//access each column from row using the array
//indexes, example header[0], header[1], header[2]...
System.out.println(Arrays.toString(header));

//reading the rows
while (scanner.hasNext()) {
    String[] row = scanner.nextLine().split(regex);

    //this is printing all columns, you can 
    //access each column from row using the array
    //indexes, example row[0], row[1], row[2]...
    System.out.println(Arrays.toString(row));
    System.out.println(row[0]);//first column (ID)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...