Most Sample Code from "Java How to Program, Sixth Edition" from Deitel and Deitel


The I/O Hierarchy:

http://java.sun.com/j2se/1.5.0/docs/api/java/io/package-tree.html

Things to consider with I/0:

  1. byte-based versus character-based
  2. sequential versus random access

The following table summarizes byte-based versus character-based I/0:

Description Super Class Sub Class(es) Sub-Sub Class
byte-based InputStream FileInputStream
ObjectInputStream
OutputStream FileOutputStream
ObjectOutputStream
character-based Reader InputStreamReader FileReader
Writer OutputStreamWriter FileWriter

Instead of using the Reader and Writer classes for character-based I/O, we will use:

For sequential files, the above classes are used. For random-access files, we will use the class:

RandomAccessFile


Class File (for Retrieving Information about Files or Directories)

Here we get input from the keyboard using a Scanner object:

Scanner input = new Scanner( System.in );

...
application.analyzePath( input.nextLine() );

The input should be a filename or directory name. A number of File functions are used. These functions are summarized in the following table (extracted from Figure 14.3, page 679 of Deitel):

Method Description
boolean exists() Returns true if the name specified as the argument to the File constructor is a file or directory in the specified path; false otherwise.
String getName() Returns a string with the name of the file or directory.
boolean isFile() Returns true if the name specifed as the argument to the File constructor is a file; false otherwise
boolean isDirectory() Returns true if the name specifed as the argument to the File constructor is a directory; false otherwise
boolean isAbsolute() Returns true if the arguments specifed to the File constructor indicate an absolute path to a file or directory; false otherwise
long lastModified() Returns a platform-dependent representation of the time at which the file or directory was last modified. The value returned is useful only for comparison with other values returned by this method.
long length() Returns the lenght of the file, in bytes. If the File object represents a directory, 0 is returned.
String getPath() Returns a string with the path of the file or directory
String getAbsolutePath() Returns a string with the absolute path of the file or directory
String getParent() Returns a string with the parent directory of the file or directory (i.e. the directory in which the file or directory can be found)
String [] list() Returns an array of strings representing the contents of a directory. Returns null if the File object does not represent a directory.

Notice the following syntax which is new to Java 1.5:

String directory[] = name.list();

...
for (String directoryName : directory )
   System.out.printf("%s\n", directoryName);

This for loop structure is new. It will cycle through each String in the array. Each iteration it will assign the current String to directoryName.


Character-Based Files (Sequential-Access)

These next three pieces of code will be making use of AccountRecord. It is declared as a package, you therefore, will compile it with the -d option:

javac -d . AccountRecord.java

This file contains fields (variables) for storing:

In addition, for each of these fields there are set and get functions for modifying and accessing the values.

Writing

In CreateTextFile, you will make use of a Formatter object. A Formatter object has the same capabilities as method System.out.printf. The line of code that create the Formatter object and enable it to write to a file called clients.txt is the following:

private Formatter output;
...
    output = new Formatter ("clients.txt");  
    ...
       output.format("%d %s %s %.2f\n", record.getAccount(), 
                record.getFirstName(), record.getLastName(), 
                record.getBalance());

The way that the output is printed to the file is dependent on the format string. This is reminiscent of C.

A single space is put between each of these values in the file.

To get the information to store in the file, you use a Scanner object to read from the keyboard. The relevant lines of code are:

Scanner input = new Scanner (System.in);  
...
   record.setAccount( input.nextInt() );  //read account number
   record.setFirstName( input.next() );   //read first name
   record.setLastName( input.next() );    //read last name
   record.setBalance( input.nextDouble() ); //read balance

When you enter input from the keyboard, I recomend that you have some negative balances, some positive balances, some zero balances (for the proper functioning of later code). Your input might look something like this:

100 Bob Jones 24.98
200 Steve Doe -345.67
300 Pam White 0.00
400 Sam Stone -42.16

500 Sue Rich 224.62

250 Tom Piper 0.00

When you are done inputting, you can take a look at the file by issuing a:

more clients.txt


Reading (using Scanner)

This code reads the clients.txt file that was created in the above section.

Notice that a Scanner object is used in ReadTextFile.java, to read clients.txt. The following lines of code are used:

 input = new Scanner ( new File ("clients.txt") );
 ...
     record.setAccount( input.nextInt() );
     record.setFirstName( input.next() );
     record.setLastName( input.next() );
     record.setBalance( input.nextDouble() );

The following code is used to output what has been read in:

System.out.printf( "%-10d%-12s%-12s%10.2f\n", 
   record.getAccount(), record.getFirstName(),
   record.getLastName(), record.getBalance() );

You will notice the %-10d format. This provides a field 10 characters wide. The negative sign (-) indicates that the field is left justified.


Extracting Data (using Scanner)

Assuming that you have the clients.txt file, you may want to extract some data from the file. If you want to extract three different things (for instance, customers with zero balances, positive balances, and negative balances), you will have to scan the file three times. Each time, you will have to close the file and reopen it to start your search from the beginning. This is the disadvantange of class Scanner, which does not provide the ability to reposition to the beginning of the file.

This code also makes use of something new from version 1.5--enum. The enum is in MenuOption.java


Writing and Reading Objects (Sequential-Access)

Writing


Reading


Random-Access Files

Creating


Writing


Reading


Using JFileChooser