CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Files

Text and Binary Files
Text files
Read from a text file

Common methods of the BufferedReader class

Method Throws Description
readLine() IOException Reads a line of text and returns it as a string.
read() IOException Reads a single character and returns it as an int that represents the ASCII code for the character. When this method attempts to read past the end of the file, it returns an int value of -1.
skip(longValue) IOException Attempts to skip the specified number of characters, and returns an int value for the actual number of characters skipped.
close() IOException Closes the input stream and flushes the buffer.

Code that reads the records in a text file

// read the records of the file
String line = in.readLine();
while(line != null)
{
    System.out.println(line);
    line = in.readLine();
}

// close the input stream
in.close();

Sample output

This application was run on Tue Jul 26 09:21:42 PDT 2011
This application was run on Wed Jul 27 10:14:12 PDT 2011

Code that reads a Product object from a delimited text file

// read the next line of the file
String line = in.readLine();

// parse the line into its columns
String[] columns = line.split("\t");
String code = columns[0];
String description = columns[1];
String price = columns[2];

// create a Product object from the data in the columns
Product p = new Product(code, description,
    Double.parseDouble(price));

// print the Product object
System.out.println(p);

// close the input stream
in.close();

Sample output from the code that reads a Product object from a delimited text file

Code:        java
Description: Murach's Beginning Java
Price:       $49.50
Previous | Connect a character output stream to a file | Write to a text file | Connect a character input stream to a file | Read from a text file | Interface with file I/O | Class with a text file | Next