ITEC 2610 Lecture Notes - Text Editor, Java Development Kit, Accounts Payable

51 views13 pages

For unlimited access to Class Notes, a Class+ subscription is required.

Week 8:
(Horstman ch.16, 16, Deite&Deitel ch.16 and Lewis&Loftus ch.8.4)
Files and I/O Streams
Storage of data in variables and arrays is temporary – the data is lost when the program terminates.
You have to use files for long-term retention of data. Like programs, files can be stored on storage
devices such as magnetic or optical disks.
Data Hierarchy. The smallest data item is the bit. The next is the character and Java uses Unicode
characters built of 2 bytes each (ie 16 bits). Some files work with characters: text files, image files,
audio files. But in many industries, such as banking, data is further organized in fields and records.
A field is a sequence of characters that convey some meaning. For instance a name can be a field.
A record contains several fields. For instance an employee record in a payroll system has:
employee number, name, pay rate, year-to-date earnings, taxes withheld (the first 2 fields are
Strings, the next 3 are doubles).
To facilitate the retrieval of specific records one field of the record is chosen as record key. In the
above example employee number is most suitable to be a record key. The most common
organization of a file of records is the random-access file, in which records are stored in order by
the record key field.
Most businesses have many different files: payroll, accounts receivable, accounts payable,
inventory etc. Often a group of files is called a database.
Files and Streams. Java views each file either as a stream of bytes or characters. Its package
java.io contains classes FileInputStream and FileOutputStream for streams of bytes and FileReader
and FileWriter for streams of characters.
Reading a Text File.
The easiest scenario is using a text file created with Notepad or any other text editor. In this case
one uses the FileReader and BufferedReader classes. The second class filters data by buffering it
into more accessible units. It uses the method readLine() to obtain a String which is then broken
into components with a StringTokenizer object. The latest versions of JDK offered in addition
classes Scanner and File, which can be used to replace BufferedReader and FileReader,
respectively.
import java.util.StringTokenizer;
import java.io.*;
import java.text.DecimalFormat;
class InventoryItem {
private String name;
private int units; // number of available units of this item
private float price; // price per unit of this item
private DecimalFormat fmt;
public InventoryItem (String itemName, int numUnits, float cost) {
Unlock document

This preview shows pages 1-3 of the document.
Unlock all 13 pages and 3 million more documents.

Already have an account? Log in
name = itemName;
units = numUnits;
price = cost;
fmt = new DecimalFormat ("0.##");
}
public String toString() {
return name + ":\t" + units + " at " + price + " = " +
fmt.format ((units * price));
}
}
public class Inventory{
//-----------------------------------------------------------------
// Reads data about a store inventory from an input file,
// creating an array of InventoryItem objects, then prints them.
//-----------------------------------------------------------------
public static void main (String[] args) {
final int MAX = 100;
InventoryItem[] items = new InventoryItem[MAX];
StringTokenizer tokenizer;
String line, name, file="inventory.dat";
int units, count = 0;
float price;
try {
BufferedReader inFile = new BufferedReader (new FileReader (file));
line = inFile.readLine();
while (line != null) {
tokenizer = new StringTokenizer (line);
name = tokenizer.nextToken();
try {
units = Integer.parseInt (tokenizer.nextToken());
price = Float.parseFloat (tokenizer.nextToken());
items[count++] = new InventoryItem (name, units, price);
}
catch (NumberFormatException exception) {
System.out.println ("Error in input. Line ignored:");
System.out.println (line);
}
line = inFile.readLine();
}
inFile.close();
for (int scan = 0; scan < count; scan++)
System.out.println (items[scan]);
}
catch (FileNotFoundException exception) {
System.out.println ("The file " + file + " was not found.");
}
catch (IOException exception) {
System.out.println (exception);
}
}
Unlock document

This preview shows pages 1-3 of the document.
Unlock all 13 pages and 3 million more documents.

Already have an account? Log in
}
The input file is shown below:
Widget 14 3.35
Spoke 132 0.32
Wrap 58 1.92
Thing 28 4.17
Brace 25 1.75
Clip 409 0.12
Cog 142 2.08
Writing a Text File.
Writing output to a text file requires the use of classes FileWriter, BufferedWriter and PrintWriter.
(or in the latest versions of JDK classes File and PrintWriter). In the example below one computes
random values which are then printed to an external file (the file is created by this program).
import java.io.*;
public class TestData {
//-----------------------------------------------------------------
// Creates a file of test data that consists of ten lines each
// containing ten integer values in the range 0 to 99.
//-----------------------------------------------------------------
public static void main (String[] args) throws IOException {
final int MAX = 10;
int value;
String file = "test.dat";
PrintWriter outFile = new PrintWriter (new BufferedWriter (new FileWriter (file)));
for (int line=1; line <= MAX; line++) {
for (int num=1; num <= MAX; num++) {
value = (int) (Math.random() * 100);
outFile.print (value + " ");
}
outFile.println ();
}
outFile.close();
System.out.println ("Output file has been created: " + file);
}
}
Sequential and Random-Access Files
What if we want to store complex objects into files ? These objects would correspond to records in
a database. Persistence is the concept that an object can “live” outside the program that created it.
Files do not have a record structure, but programs can impose a record structure on a file. Java
contains a mechanism called object serialization, which transforms an object into a sequence of
bytes. Any object that we want to serialize must implement the interface Serializable. To serialize
one uses the method writeObject() of the class ObjectOutputStream, which works in conjunction
with the class FileOutputStream.
Unlock document

This preview shows pages 1-3 of the document.
Unlock all 13 pages and 3 million more documents.

Already have an account? Log in

Get access

Grade+
$10 USD/m
Billed $120 USD annually
Homework Help
Class Notes
Textbook Notes
40 Verified Answers
Study Guides
1 Booster Class
Class+
$8 USD/m
Billed $96 USD annually
Homework Help
Class Notes
Textbook Notes
30 Verified Answers
Study Guides
1 Booster Class