READING DATA FROM A TEXT FILE: FileReader

advertisement
READING DATA FROM A TEXT FILE:
The FileReader and BufferedReader Classes
The FileReader and BufferedReader classes are part of the java.io package and are used together to
read the contents of a file(s). The FileReader object is used to create an input file stream, while the
BufferedReader object is used to read data from the stream.
The following is a list of some of the constructors and methods included in the FileReader and
BufferedReader classes:
CONSTRUCTOR
DESCRIPTION
FileReader(File fileName)
Creates an input file stream for the File object. Throws a
FileNotFoundException exception if the file does not exist.
FileReader(String path)
Creates an input file stream from the specified path name.
Throws a FileNotFoundException exception if the file does not
exist.
BufferedReader(Reader
stream)
Creates a buffered stream reader from the FileReader object.
METHODS
DESCRIPTION
void close()
Closes the input file stream object. Throws IOException if the
file cannot be closed.
int read()
Reads a single character from the file and returns it as an integer.
Returns -1 if the end of the file has been reached. Throws
IOException if the stream cannot be read.
String readLine()
Reads a line of text from the input stream and returns it as a
String. Returns null if the end of the line has been reached.
Throws IOException if stream cannot be read.
The following program reads from a file named movies.txt which contains the names of five movies, the
studio company, and the amount of money each movie has grossed so far.
import java.io.*;
public class FileReaderExample {
public static void main(String[] args) {
// Declare and initialize File object
File txtFile = new File(“H:\\My Documents\\movies.txt”);
Reading Data from a Text File
Page 1 of 6
// Declare String variable
String line;
try
{
// Initialize FileReader and BufferedReader objects
BufferedReader in = new BufferedReader(new FileReader
(txtFile));
// Read the first line from the text file
line = in.readLine();
// Read and output lines of text
while (line != null)
{
System.out.println(line);
line = in.readLine();
}
// Close BufferedReader stream
in.close();
}
// Output error message if exception is thrown
catch (IOException e)
{
System.err.println(“IOException:” + e.getMessage());
}
}
}
The above code will produce the following output:
Reading Data from a Text File
Page 2 of 6
READING NUMERIC DATA
Data on a disk is a set of characters. So even though the data in a file may contain numeric data, it is
read and understood as characters. In order to read numeric data as numbers, the characters must be
converted using the parseDouble() and parseInt() methods included in the Double and Integer
classes respectively. Both methods returns numeric values from String data – a double value in the case
of parseDouble() and an integer value in the case of parseInt().
The following is an example of a program that reads the hourly wage rates of five employees that are
stored in a text file and then calculates and outputs the average hourly wage:
import java.io.*;
import java.text.*;
public class WagePerHour {
public static void main(String[] args) {
// Declare and initialize File and DecimalFormat objects
File dataFile = new File("H:\\My Documents\\wages.txt");
DecimalFormat df = new DecimalFormat("$0.00");
// Declare variables
String wage;
double avgWage, total = 0;
int numWages = 0;
try
{
// Initialize FileReader and BufferedReader objects
BufferedReader in = new BufferedReader(new
FileReader(dataFile));
wage = in.readLine();
// Read each line of data until it reaches the end
while (wage != null)
{
numWages += 1;
Reading Data from a Text File
Page 3 of 6
total += Double.parseDouble(wage);
System.out.println(df.format(wage));
wage = in.readLine();
}
// Calculate and output average hourly wage
avgWage = total / numWages;
System.out.println("\nAVERAGE = " + df.format(avgWage));
// Close BufferedReader stream
in.close();
}
// Output error message if exception is thrown
catch (IOException e)
{
System.err.println("IOException: " + e.getMessage());
}
}
}
The above code produces the following output:
READING TAB-DELIMITED AND COMMA-DELIMITED DATA FILES
Typically, text files use special characters called delimiters to separate elements of a file. For example,
if I wanted a file to store the names and hourly wages of each employee, I can store each person’s name
and hourly wage on one line and separate the individual fields (i.e. name and wage) using a delimiter.
There are typically two types of delimiters that are commonly used in data files:
(i)
(ii)
COMMA-DELIMITED:
TAB-DELIMITED:
Uses commas to separate individual fields
Uses tabs to separate fields.
When reading a line of data from a file, you can use the split() method included in the String class to
separate the line into the individual strings that are separated by commas or tabs and store each
individual string as an element in an array. Here’s an example of a program that reads from a commadelimited file where each line contains an employee’s name and his/her corresponding hourly wage:
Reading Data from a Text File
Page 4 of 6
import java.io.*;
import java.text.*;
public class Delimiters {
public static void main(String[] args) {
// Declare and initialize File and DecimalFormat objects
File dataFile = new File("H:\\My
Documents\\delimiters.txt");
DecimalFormat df = DecimalFormat("$0.00");
// Declare variables
String line;
double average = 0;
int numWages = 0;
// Declare a String array to store data from each line
String[] data;
// Output column headings
System.out.printf("%-20s%-20s\n", "NAME", "HOURLY WAGE");
try
{
// Initialize FileReader and BufferedReader objects
BufferedReader in = new BufferedReader(new
FileReader(dataFile));
line = in.readLine();
while (line != null)
{
// Read individual lines of data from file
data = line.split(", ");
numWages++;
average += Double.parseDouble(data[1];
Reading Data from a Text File
Page 5 of 6
System.out.printf("%-20s%-20s", data[0],
df.format(Double.parseDouble(data[1])));
line = in.readLine();
}
// Close BufferedReader stream
in.close();
// Calculate and output average wage
average = average / numWages;
System.out.printf("\n%-20s%-20s", "AVERAGE:",
df.format(average));
}
// Output error message if exception is thrown
catch (IOException e)
{
System.err.println("IOException: " + e.getMessage());
}
}
}
The above code produces the following output:
Reading Data from a Text File
Page 6 of 6
Download