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..
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.
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.
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.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With