Home
9. Reading a Text File
Tips!
Let's read some data from an external source to combine all we learned before...
With a free online tool we create a test CSV file with random data. This file is stored in a subdirectory resources
as testdata.csv
.
The file in the source code contains comma-separated values for counter, firstname, lastname, age, Street, City, State, ZIP:
1,Ada,Gomez,40,Mabvob Pike,Radafso,LA,60500 2,Bernard,Jordan,28,Dotcu Court,Cewbufbim,MS,17422 3,Mittie,Vaughn,64,Nandac Mill,Patunif,RI,81182 4,Miguel,Clarke,39,Liac Boulevard,Deguci,NH,32207 ...
Let's write a program to read this CSV-file line by line and convert each line to an object which is added to a list of persons:
Just like in the UsingObjects-example, we use an object to store the data of each line in the CSV file, in this case, the object Person
.
Within the loadPersons-method:
- the file is opened
- read line by line
- the text of each line is used to create a Person-object
- this object is added to the list
- the list is returned.
Within the main-method, the resulting list is used:
- to count the number of persons on the list
- to print each person's full name and age
$ java ReadTextFile.java Number of persons loaded from CSV file: 100 Ada Gomez, age: 40 Bernard Jordan, age: 28 Mittie Vaughn, age: 64 Miguel Clarke, age: 39 ...