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
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.
Are the columns delimited by tabs?
Look at Java CSV, an open source library for reading comma delimited or tab delimited text files. SHould do most of the job. I've never used it myself, but I assume you'd be able to ask for all the values from column 1 (or similar).
Alternatively, you could read the file one line at a time using a BufferedReader
(which has a readLine()
) method) and then call String.split()
and grab the parts you want.