Labs
The focus of this set of labs is reading, parsing, and writing files.
- Create a class named
SearchEmployeesthat searches through the file employee.txt for the pattern "manager", and prints out any lines that match the pattern. (Hint: You can search through a string for a substring using theindexOforcontainsmethods in theStringclass.)
(Solution: SearchEmployees.java)
- Add code to
PlanetReaderto open planets.txt and read it one line at a time. As it reads each line, have it print just the planet's name. (Hint:String.split.)
(Solution: PlanetReader.java)
- Modify
PlanetReader. After reading a record, it should use the fields to construct aPlanetobject, then print it usingPlanet'stoString.
(Solution: PlanetReader2.java)
- Modify
PlanetReader. InreadPlanetsadd a local variable of typeList<Planet>initialized with anArrayList. While reading from the file, instead of printing thePlanet, add it to the list. Change thereadPlanetsreturn type fromvoidtoList<Planet>, and return the list after the file is closed. Inmain, assign the returned list to a local variable and print it.
(Solution: PlanetReader3.java)
- Modify
PlanetReader. Create awritePlanetsmethod that takes aStringfilename and aList<Planet>parameter. It should open the named file for output, and for each planet, write its name, orbit, and diameter to the file, separated by tab (\t) characters. Make sure you don't use planets.txt as the output file name! Check the results in your output file by opening it with the Eclipse Text Editor (Hint: In Eclipse, when a program creates a file in your project, Eclipse won't notice and display it until you do a File | Refresh (or F5.)
(Solution: PlanetReader4.java)
planets.txt
Mercury, 57910000, 4880
Venus, 108200000, 12103
Earth, 149600000, 12756
Mars, 227940000, 6794
Jupiter, 778330000, 142984
Saturn, 1429400000, 120536
Uranus, 2870990000, 51118
Neptune, 4504000000, 49532