Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

file-io

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 age
01 ron   21
02 harry 12
03 tom   23
04 jerry 25
-------------

from the above data if I need to gather the column "name" using list in java and print it..

like image 525
Venkat Pathy Avatar asked Jan 31 '12 17:01

Venkat Pathy


People also ask

How do you read a text file and store it to an ArrayList in java?

This Java code reads in each word and puts it into the ArrayList: Scanner s = new Scanner(new File("filepath")); ArrayList<String> list = new ArrayList<String>(); while (s. hasNext()){ list. add(s.

How do you read a specific text file in java?

There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader, or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability.

How do you read the contents of a file into a String in java?

The readString() method of File Class in Java is used to read contents to the specified file. Return Value: This method returns the content of the file in String format. Note: File. readString() method was introduced in Java 11 and this method is used to read a file's content into String.


Video Answer


2 Answers

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<String> names = new ArrayList<String>();

// 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);
}
like image 195
hmjd Avatar answered Oct 19 '22 12:10

hmjd


Use a file reader and read it line by line, break on the spaces and add any column you want to the List. Use a BufferedReader to grab the lines by something like this:

BufferedReader br = new BufferedReader(new FileReader("C:\\readFile.txt"));

Then you can do to grab a line:

String line = br.readLine();

Finally you can split the string into an array by column by doing this:

String[] columns = line.split(" ");

Then you can access the columns and add them into the list depending on if you want column 0, 1, or 2.

like image 41
Michael Boselowitz Avatar answered Oct 19 '22 12:10

Michael Boselowitz