The basic idea is that you create a file reader object
FileReader fr = new FileReader('file.txt');
and then go over the file line by line parsing each line and saving the stuff to some internal data storage (Array, HashMap).
The while loop in the example you have does just this. The FileReader
class will take care of the line ending for you, and will return null
when there's no more lines to be read. What you need to do inside the while loop is to parse each line and separate the different bits of data (course name, price etc.) from each other.
EDIT: To parse the lines you would do something like the following. What is inside the while loop depends on how you format the menu files. The following works on the assumption that the menu files contains the price and the name of the course (in that order) separated by a comma on each line.
12.95$,Penne ala Arabiata
8.15$,Fish Soup
Notice that you can't use a comma in the price if you do this. You can of course use a semicolon as the separator between the data fields instead of a comma. The number of data fields is of course also up to you.
String line = "";
// read lines from file
while ((line = fr.readLine()) != null) {
// parse each line
tokens = line.split(",");
String price = tokens[0];
String courseName = tokens[1];
// extract all other information
}
In your final code you'll want to save the data fields into some structure instead of just extracting them from the file. Another thing to note is that the price is a String NOT a number because of the dollar sign. Should you wish to do any calculations with the prices you'll of course need the convert it to a number with parseFloat()
or parseDouble()
.
And of course if you do use the csv (comma separated values) format, it's better to go for a csv library to do the parsing for you instead of writing the parser yourself.
http://opencsv.sourceforge.net/