Reading sample column data from a text file to a list in Java

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

For example: if the text file data looks like this

------------- id name age 01 ron 21 02 harry 12 03 tom 23 04 jerry 25 ------------- 

from the above data, if I need to collect the column β€œname” using a list in java and print it.

+4
source share
3 answers

Use a file reader and read it line by line, break spaces and add any column to the list. Use BufferedReader to capture lines as follows:

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

Then you can do to capture the line:

 String line = br.readLine(); 

Finally, you can split a row into an array by column by doing the following:

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

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

+3
source

java.util.Scanner can be used to read the file, discarding unwanted columns. Either print the desired column values ​​when processing the file, or add() before java.util.ArrayList and print them after 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); } 
+1
source

Are tabbed columns separated?

Check out Java CSV , an open source library for reading comma-separated or tab delimited text files. Should do most of the work. I have never used it myself, but I assume that you can query all the values ​​from column 1 (or similar).

Alternatively, you can read the file one line at a time using BufferedReader (which has the readLine() method), and then call String.split() and take the parts you need.

0
source

Source: https://habr.com/ru/post/1394024/


All Articles