Java Program
This is an example of how to read a record from a comma delimited text file and split out the individual fields in each record. The “items.txt” file has records that contain the following fields:
· itemNumber, numeric identification number (int)
· description, text description of item (String)
· quantity, number of items of this type (int)
· unitCost, value of each item (double)
To use a comma (,) as the delimiter, File file = new File("C:/Data/items.txt"); // Create a Scanner object for this file.
Scanner input = new Scanner(file); input.useDelimiter(",");
You can then read a record and split it into separate fields, separated by commas like this:
while (input.hasNext()) {
String record = input.nextLine();
String tokens[] = record.split(",");
int itemNumber = Integer.parseInt(tokens[0]);
String description = tokens[1];
int quantity = Integer.parseInt(tokens[2]);
double unitCost = Double.parseDouble(tokens[3]);