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

前端 未结 3 1561
栀梦
栀梦 2021-01-02 17:29

Can someone help me to read a selective column of data in a text file into a list..

e.g.: if the text file data is as follows

-------------
id name a         


        
3条回答
  •  离开以前
    2021-01-02 18:02

    java.util.Scanner could be used to read the file, discarding the unwanted columns. Either print the wanted column values as the file is processed or add() them to a java.util.ArrayList and print them once processing is complete.

    A small example with limited error checking:

    Scanner s = new Scanner(new File("input.txt"));
    List names = new ArrayList();
    
    // Skip column headings.
    
    // Read each line, ensuring correct format.
    while (s.hasNext())
    {
        s.nextInt();         // read and skip 'id'
        names.add(s.next()); // read and store 'name'
        s.nextInt();         // read and skip 'age'
    }
    
    for (String name: names)
    {
        System.out.println(name);
    }
    

提交回复
热议问题