SDSU CS 596 Java Programming
Fall Semester, 1998
Java IO part 2
To Lecture Notes Index
© 1998, All Rights Reserved, SDSU & Roger Whitney
San Diego State University -- This page last updated 21-Dec-98

Contents of Doc 16, Java IO part 2


References


The Java Programming Language , 2 nd Ed., Arnold and Gosling, Chapter 12

On-line Java Documentation

Java source code


Listen Here!S-oct21 6mins, Q-oct22 4mins Doc 16, Java IO part 2 Slide # 2

File

java.io.File contains constants for and operations on files and directories.

Constants
pathSeparator ( unix = : )
The system dependent path separator string.
pathSeparatorChar ( unix = : )
The system dependent path separator character.
separator ( unix = / )
The system dependent file separator String.
separatorChar ( unix = / )
The system dependent file separator character.

Constructors
File(String)
Creates a File object.
File(String, String)
Creates a File object from the specified directory.
File(File, String)
Creates a File object (given a directory File object).

File Methods (JDK 1.1)
canRead()
getName()
lastModified()
canWrite()
getParent()
length()
delete()
getPath()
list()
equals(Object)
hashCode()
list(FilenameFilter)
exists()
isAbsolute()
mkdir()
getAbsolutePath()
isDirectory()
mkdirs()
getCanonicalPath()
isFile()
renameTo(File)


toString()

Methods Added in JDK 1.2
compareTo(File pathname)
exists()
listFiles(FileFilter filter)
compareTo(Object o)
getAbsoluteFile()
listFiles(filter)
createNewFile()
getCanonicalFile()
static File[] listRoots()
static createTempFile(pattern, directory)
getParentFile()
setLastModified(time)
static createTempFile(prefix)
isHidden()
setReadOnly()
deleteOnExit()
listFiles()
toURL()
equals(Object obj)




Doc 16, Java IO part 2 Slide # 3
File Info

A file is specified by a pathname, either

absolute pathname
pathname relative to the current working directory

The pathname must follow the naming conventions of the host platform.


Listen Here!S-oct21 2mins, Q-oct22 2mins Doc 16, Java IO part 2 Slide # 4
Creating Directories

import java.io.File;
import java.io.IOException;
class CreatingDirectories
   {
   public static void main( String args[] ) throws IOException
      {
      // One directory
      File courseDirectory = new File( "cs535" );
      courseDirectory.mkdir();
      
      // Subdirectory
      File gradesDirectory = new File( "cs535/grades" );
      gradesDirectory.mkdir();
      
      // Multiple directories
      // test and this must exist before this will work
      File  oneAtATime  =  new File(  "test/this/out"  );
      boolean createResult = oneAtATime.mkdir();
      if ( createResult )
         System.out.println( "Created test/this/out");
      else
         System.out.println( "Failed to create test/this/out");
      // creates all four directories at once
      File  severalAtOnce  =  new File( "second/test/of/this"  );
      
      if ( !severalAtOnce.exists() )
         createResult = severalAtOnce.mkdirs();
      }
   }
Output
Failed to create test/this/out
Created second/test/of/this

Listen Here!S-oct21 3mins, Q-oct22 4mins Doc 16, Java IO part 2 Slide # 5
Creating Files
import java.io.*;
class Test
   {
   public static void main( String args[] ) throws IOException
      {
      // Open/Create file for writing
      FileWriter writeableFile = new FileWriter( "RightHere" );
      
      // Open file for reading, IOException if does not exists
      FileReader info = new FileReader( "ReadMe");
      
      // Safer Way
      File readMe = new File( "ReadeMe" );
      FileReader moreInfo;
      if ( readMe.exists() )
         moreInfo = new FileReader( readMe );
      
      // Open/Create file for appending
      boolean append = true;
      FileWriter exam = new FileWriter( "exam", append );
      PrintWriter cout = new PrintWriter( 
            new BufferedWriter( exam ));
      
      cout.println( "Question One: Write a class to...");
      cout.close();
      }
   }

Doc 16, Java IO part 2 Slide # 6
Some File Data
import java.io.*;
import java.util.*
class FileInfo
   {
   public static void main( String args[] ) throws IOException
      {
      File exam = new File( "Exam" );
      System.out.println( "Absolute Path: " + 
                              exam.getAbsolutePath()  );
      System.out.println( "Path: " + exam.getPath()  );
      System.out.println( "Name: " + exam.getName()  );
      System.out.println( "Parent: " + exam.getParent()  );
      System.out.println( "Can read: " + exam.canRead()  );
      System.out.println( "Can write: " + exam.canWrite()  );
      System.out.println( "Length: " + exam.length()  );
      System.out.println( "Modified?: " + exam.lastModified()  );
      System.out.println( "Modified!: " + 
                              new Date(exam.lastModified())  );
      }
   }
Output
Absolute Path: /Programming/JavaPrograms/classNotes/Exam
Path: Exam
Name: Exam
Parent: null
Can read: true
Can write: true
Length: 710
Modified?: 877380994000
Modified!: Mon Oct 20 12:56:34 ADT 1997

Listen Here!S-oct21 2mins Doc 16, Java IO part 2 Slide # 7
Machine Independence

Be careful about embedding Unix (Dos, Mac) specific files names in programs

import java.io.*;
class  MachineIndependentFileNames
   {
   public  static  void  main( String  args[]  )
      {
      String  macFile  =  ":home:ma:whitney:cs596:grades";
      String currentPlatformFile
           =  macFile.replace( ':', File.separatorChar );
      }
   }

Listen Here!S-oct21 32secs Doc 16, Java IO part 2 Slide # 8
Listing all files in a Directory

import java.io.*;
class ListAll
   {
   public static void main( String args[] ) throws IOException
      {
      File currentDirectory = new File( "." );
      String[] listing = currentDirectory.list();
      
      for ( int k = 0; k < listing.length; k++ )
         System.out.println( listing[k] );
      }
   }
Output
Property
randomNumbers.html
randomNumbers.java
readableSerialize.html
readableSerialize.java
ReadingFileExample.java

Listen Here!S-oct21 1min Doc 16, Java IO part 2 Slide # 9
Listing all .html files in a Directory
The following is the "wrong" way to list all files with a given ending. See the next slide for the "correct" way.

import java.io.*;
class TheNoReuseWay
   {
   public static void main( String args[] ) throws IOException
      {
      File currentDirectory = new File( "." );
      String[] listing = currentDirectory.list();
      
      for ( int k = 0; k < listing.length; k++ )
         if ( listing[k].endsWith( ".html" ))
            System.out.println( listing[k] );
      }
   }
Output
randomNumbers.html
readableSerialize.html

Listen Here!S-oct21 2mins Doc 16, Java IO part 2 Slide # 10
Listing all .html files in a Directory With Reuse
To list all files that meet some criteria create a subclass of FilenameFilter. This class can be use in other programs. It can also be used by the FileDialog window in AWT. You could use sdsu.io.FileExtensionFilter if you are interested in just files with a given ending.

import java.io.*;
class Test {
   public static void main( String args[] ) throws IOException {
      File currentDirectory = new File( "." );
      String[] listing = currentDirectory.list( 
            new FileExtensionFilter("html"));
      
      for ( int k = 0; k < listing.length; k++ )
         System.out.println( listing[k] );
   }
}
public class FileExtensionFilter implements FilenameFilter {
   String fileExtension;
   
   public FileExtensionFilter( String extension ) {
      if ( extension.startsWith( "." ))
         fileExtension = extension;
      else
         fileExtension = "." + extension;
   }
    public  boolean accept(File dir, String name) {
      if ( name.endsWith( fileExtension ) )
         return true;
      else
         return false;
   }
}

Listen Here!S-oct21 2mins Doc 16, Java IO part 2 Slide # 11

Formatting


C and C++ allow programmers to format numbers by specifying such things as the number of digits to be displayed. Java's formatting classes handle formatting of numbers and dates in different countries and languages. Hence, formatting in Java is a bit more complex.

Internationalization Issues

Are dates formatted as:
10/13/97
13/10/97
13.10.97

Are numbers formatted as:
1,234.56
1.234,56
1;234.56


Listen Here!S-oct21 2mins Doc 16, Java IO part 2 Slide # 12
Java's Solution - Locales

An instance of the java.util.Locale class contains the rules for formatting in a language in a location. Each Java virtual machine has a default instance of the Locale class, which should be for the local language rules in the current country.

java.text.NumberFormat

Formats numbers, currency, and percents using the default Locale rules

For finer control over formatting numbers use java.text.DecimalFormat

java.text.DateFormat

Formats dates and time using the default Locale rules

Dates and times can be formatted in FULL, LONG, MEDIUM, and SHORT versions

For finer control over formatting dates use java.text.SimpleDateFormat

Listen Here!S-oct21 2mins Doc 16, Java IO part 2 Slide # 13
Using the Default Locale to Format

class FormatUsingLocalRules
   {
   public static void main( String args[] ) throws Exception
      {
      NumberFormat number = NumberFormat.getInstance(  );
      NumberFormat currency = 
            NumberFormat.getCurrencyInstance(  );
      DateFormat shortDate = 
            DateFormat.getDateInstance(DateFormat.SHORT);
      DateFormat fullTime = 
            DateFormat.getTimeInstance(DateFormat.FULL );
      
      System.out.println( "Number: " + number.format( 123456 ));
      System.out.println( "Currency: " + 
                              currency.format( 1234.56 ));
      System.out.println( "ShortDate: " + 
                              shortDate.format( new Date() ));
      System.out.println( "FullTime: " + 
                              fullTime.format( new Date() ));
      }
   }
Output
Number: 123,456
Currency: $1,234.56
ShortDate: 10/13/97
FullTime: 5:15:42 oclock PM PDT

Listen Here!S-oct21 2mins Doc 16, Java IO part 2 Slide # 14
International Example

Explicitly use other locales to show that they are different. Usually you do not want to use locales explicitly.

class FormatExplicitlyCallingDifferentLocale
   {
   public static void main( String args[] )
      {
      System.out.println( "-------US English------");
      internationalPrint( Locale.getDefault() );
      System.out.println( "-------Canadian English------");
      internationalPrint( new Locale("en", "CA" ));
      System.out.println( "-------Spanish Spanish------");
      internationalPrint( new Locale("es", "ES" ));
      System.out.println( "-------German German------");
      internationalPrint( new Locale("de", "DE" ));
      }
//internationalPrint on next slide

Listen Here!S-oct21 16secs, Q-oct22 10mins Doc 16, Java IO part 2 Slide # 15
//International Example - continued

   public static void internationalPrint( Locale custom )
      {
      NumberFormat number = 
               NumberFormat.getInstance( custom );
      NumberFormat currency = 
               NumberFormat.getCurrencyInstance( custom );
      DateFormat shortDate = DateFormat.getDateInstance(
                            DateFormat.SHORT, custom );
      DateFormat fullDate = DateFormat.getDateInstance( 
                           DateFormat.FULL, custom );
      DateFormat shortTime = DateFormat.getTimeInstance( 
                           DateFormat.SHORT, custom );
      DateFormat longTime = DateFormat.getTimeInstance(
                           DateFormat.LONG,custom );
      System.out.println( "Number: " + 
                        number.format( 123456 ));
      System.out.println( "Currency: " + 
                        currency.format( 1234.56 ));
      System.out.println( "ShortDate: " + 
                        shortDate.format( new Date() ));
      System.out.println( "FullDate: " + 
                        fullDate.format( new Date() ));
      System.out.println( "ShortTime: " + 
                        shortTime.format( new Date() ));
      System.out.println( "LongTime: " + 
                        longTime.format( new Date() ));
      }
   }

Listen Here!S-oct21 4mins Doc 16, Java IO part 2 Slide # 16
//International Example - continued

Output
-------US English------
Number: 123,456
Currency: $1,234.56
ShortDate: 10/12/97
FullDate: Sunday, October 12, 1997
ShortTime: 9:45 PM
LongTime: 9:45:46 PM PDT
-------Canadian English------
Number: 123;456
Currency: $1;234.56
ShortDate: 12/10/97
FullDate: Sunday, October 12, 1997
ShortTime: 9:45 PM
LongTime: 9:45:46 PDT PM
-------Spanish Spanish------
Number: 123.456
Currency: 1.234,56 Pts
ShortDate: 13/10/97
FullDate: lunes 13 de octubre de 1997
ShortTime: 6:45
LongTime: 6:45:46 GMT+02:00
-------German German------
Number: 123.456
Currency: 1.234,56 DM
ShortDate: 13.10.97
FullDate: Montag, 13. Oktober 1997
ShortTime: 06:45
LongTime: 06:45:46 GMT+02:00

Listen Here!S-oct21 3mins Doc 16, Java IO part 2 Slide # 17

Static and Dynamic Text

MessageFormat allows us to create temples with placeholders. At runtime, we can replace the placeholders with actual values. The example below shows how to do this.

import java.text.MessageFormat;
import java.util.Date;
class Test
   {
   public static void main( String args[] ) throws Exception
      {
      Object[] dynamicText = {"Roger",new Date() };
      
      String staticText = "{0}, it is {1,time,short}";
      String publicMessage = 
         MessageFormat.format(staticText, dynamicText);
      System.out.println( publicMessage );
      }
   }
Output
Roger, it is 10:03 PM  

Listen Here!S-oct21 2mins, Q-oct22 2mins Doc 16, Java IO part 2 Slide # 18

StreamTokenizer

The StreamTokenizer is useful in parsing text into tokens.

Methods
commentChar(int) pushBack()
eolIsSignificant(boolean) quoteChar(int)
lineno() resetSyntax()
lowerCaseMode(boolean) slashSlashComments(boolean)
nextToken() slashStarComments(boolean)
ordinaryChar(int) toString()
ordinaryChars(int, int) whitespaceChars(int, int)
parseNumbers() wordChars(int, int)


StreamTokenizer

More complex than the StringTokenizer
Designed to parse "Java-style" input
Parses numbers
Parses Java-style comments


Doc 16, Java IO part 2 Slide # 19
nextToken

Returns the type of the next token

Places token type in field ttype

Places the token in a public field

sval for string (or word )
nval for number (declared a double not Double)

Token Types

TT_WORD
A string (word) was scanned
The string field sval contains the word scanned
TT_NUMBER
A number was scanned
Only decimal floating-point numbers (with or without a decimal point) are recognized
TT_EOL
End-of-line scanned
TT_EOF
End-of-file scanned


Listen Here!S-oct21 4mins Doc 16, Java IO part 2 Slide # 20
Simple Example
import java.io.*;
class  Tokenizer  
   {
   public static void main( String args[] ) throws Exception 
      {
      String sample = "this 123 is an 3.14 \n simple test";
      InputStream in;
      in = new StringBufferInputStream( sample );
      StreamTokenizer parser = new StreamTokenizer( in );
      
      while ( parser.nextToken() != StreamTokenizer.TT_EOF )
         {
         if ( parser.ttype == StreamTokenizer.TT_WORD)
            System.out.println( "A word: " + parser.sval );
         else if  ( parser.ttype == StreamTokenizer.TT_NUMBER )
            System.out.println( "A number: " + parser.nval );
         else if  ( parser.ttype == StreamTokenizer.TT_EOL )
            System.out.println( "EOL" );
         else
            System.out.println( "Other: " + (char) parser.ttype );
         }   
      }
   }
Output
A word: this
A number: 123
A word: is
A word: an
A number: 3.14
A word: simple
A word: test

Listen Here!Q-oct22 5mins Doc 16, Java IO part 2 Slide # 21
Terms and Defaults
Special Characters
Characters that are treated special
White space
Characters that make up numbers
Characters that make up words (tokens)

Ordinary Characters
All nonspecial characters

Default Values

Word characters
a - z
A - Z
ASCII values 130 through 255

White space
ASCII values 0 through 32
includes space, tab, line feed, carriage return, escape

comment character /
quote characters " (double quote) ' (single quote )
parse numbers on

Default to OFF
eolIsSignificant are ends of line significant
lowerCaseMode converts all to lower case
slashSlashComments recognize /* */ comments
slashStarComments recognize // comments

Listen Here!Q-oct22 4mins Doc 16, Java IO part 2 Slide # 22
Warning In JDK 1.1

Documentation states:

  public void resetSyntax()
      Resets the syntax table so that all characters are special. 

Source code states:

  public void resetSyntax()
      Resets the syntax table so that all characters are special. 

Source code does:

  public void resetSyntax()
      Resets the syntax table so that all characters are ordinary. 

In JDK 1.2, the documentation and the source code are consistent. resetSyntax() sets all character types to ordinary.

Listen Here!Q-oct22 7mins Doc 16, Java IO part 2 Slide # 23
EOL Example
import java.io.*;
class  Tokenizer  
   {
   public static void main( String args[] ) throws Exception 
      { 
      String sample = "this 123 is an 3.14 \n simple test";
      InputStream in =  new StringBufferInputStream( sample );
      StreamTokenizer parser = new StreamTokenizer( in );
      parser.eolIsSignificant( true ); 
      
      while ( parser.nextToken() != StreamTokenizer.TT_EOF )
         {
         if ( parser.ttype == StreamTokenizer.TT_WORD)
            System.out.println( "A word: " + parser.sval );
         else if  ( parser.ttype == StreamTokenizer.TT_NUMBER )
            System.out.println( "A number: " + parser.nval );
         else if  ( parser.ttype == StreamTokenizer.TT_EOL )
            System.out.println( "EOL" );
         else
            System.out.println( "Other: " + (char) parser.ttype );
         }   
      }
   }
Output
A word: this
A number: 123
A word: is
A word: an
A number: 3.14
EOL
A word: simple
A word: test

Listen Here!Q-oct22 4mins Doc 16, Java IO part 2 Slide # 24
Default Comment Character

import java.io.*;
class  Tokenizer  
   {
   public static void main( String args[] ) throws Exception 
      { 
      String sample = "this 123 /is an 3.14 \n simple test";
      InputStream in = new StringBufferInputStream( sample );
      StreamTokenizer parser = new StreamTokenizer( in );
      
      while ( parser.nextToken() != StreamTokenizer.TT_EOF )
         {
         if ( parser.ttype == StreamTokenizer.TT_WORD)
            System.out.println( "A word: " + parser.sval );
         else if  ( parser.ttype == StreamTokenizer.TT_NUMBER )
            System.out.println( "A number: " + parser.nval );
         else if  ( parser.ttype == StreamTokenizer.TT_EOL )
            System.out.println( "EOL" );
         else
            System.out.println( "Other: " + (char) parser.ttype );
         }   
      }
   }
Output
A word: this
A number: 123
A word: simple
A word: test

Doc 16, Java IO part 2 Slide # 25
Quote Character

import java.io.*;
class  Tokenizer  
   {
   public static void main( String args[] ) throws Exception 
      { 
      String sample = "this #123 /is an 3.14# \n simple test";
      InputStream in = new StringBufferInputStream( sample );
      StreamTokenizer parser = new StreamTokenizer( in );
      parser.quoteChar( '#' );
      while ( parser.nextToken() != StreamTokenizer.TT_EOF )
         {
         if ( parser.ttype == StreamTokenizer.TT_WORD)
            System.out.println( "A word: " + parser.sval );
         else if  ( parser.ttype == StreamTokenizer.TT_NUMBER )
            System.out.println( "A number: " + parser.nval );
         else if  ( parser.ttype == StreamTokenizer.TT_EOL )
            System.out.println( "EOL" );
         else
            System.out.println( "Other: " + (char) parser.ttype +
                           "sval: " + parser.sval );
         }   
      }
   }
Output
A word: this
Other: #sval: 123 /is an 3.14
A word: simple
A word: test

Listen Here!Q-oct22 5mins Doc 16, Java IO part 2 Slide # 26
\n always counts between Quote Characters

import java.io.*;
class  Tokenizer  
   {
   public static void main( String args[] ) throws Exception 
      { 
      String sample = "this #123 /is an 3.14 \n simple # test";
      InputStream in = new StringBufferInputStream( sample );
      StreamTokenizer parser = new StreamTokenizer( in );
      parser.quoteChar( '#' );
      while ( parser.nextToken() != StreamTokenizer.TT_EOF )
         {
         if ( parser.ttype == StreamTokenizer.TT_WORD)
            System.out.println( "A word: " + parser.sval );
         else if  ( parser.ttype == StreamTokenizer.TT_NUMBER )
            System.out.println( "A number: " + parser.nval );
         else if  ( parser.ttype == StreamTokenizer.TT_EOL )
            System.out.println( "EOL" );
         else
            System.out.println( "Other: " + (char) parser.ttype +
                           "sval: " + parser.sval );
         }   
      }
   }
Output
A word: this
Other: #sval: 123 /is an 3.14 
A word: simple
Other: #sval:  test

Doc 16, Java IO part 2 Slide # 27
Some Parsing Fun
import java.io.*;
class  Tokenizer  {
   public static void main( String args[] ) throws Exception { 
      String sample = "this #123 /is an 3.14 \n simple # test";
      InputStream in = new StringBufferInputStream( sample );
      StreamTokenizer parser = new StreamTokenizer( in );
      parser.wordChars( 0, 255 );
      parser.ordinaryChar( 's' );
      while ( parser.nextToken() != StreamTokenizer.TT_EOF )
         {
         if ( parser.ttype == StreamTokenizer.TT_WORD)
            System.out.println( "A word: " + parser.sval );
         else if  ( parser.ttype == StreamTokenizer.TT_NUMBER )
            System.out.println( "A number: " + parser.nval );
         else if  ( parser.ttype == StreamTokenizer.TT_EOL )
            System.out.println( "EOL" );
         else
            System.out.println( "Other: " + (char) parser.ttype +
                           "sval: " + parser.sval );
         }   
      }
   }
Output
A word: thi
Other: ssval: null
A word: #123 /i
Other: ssval: null
A word: an 3.14 
 
Other: ssval: null
A word: imple # te
Other: ssval: null
A word: t

Doc 16, Java IO part 2 Slide # 28
Getting Fancy

class  Tokenizer  
   {
   public static void main( String args[] ) throws Exception 
      { 
      String sample = "name with space=value # a commment\n; "
                     + " 'sam =cat' = \n A";
      InputStream in = new StringBufferInputStream( sample );
      StreamTokenizer parser = new StreamTokenizer( in );
      parser.wordChars( 0, 255 );
      parser.whitespaceChars( 9, 13 ); //tab, line feed, return
      parser.ordinaryChar( ';' );
      parser.ordinaryChar( '=' );
      parser.commentChar( '#' );
      parser.quoteChar( '\'' );
      while ( parser.nextToken() != StreamTokenizer.TT_EOF )
         {
         // Same as other examples
         }   
      }
   }
Output
A word: name with space
Other: =sval: null
A word: value 
Other: ;sval: null
Other: 'sval: sam =cat
Other: =sval: null
A word: A

Copyright © 1998 SDSU & Roger Whitney, 5500 Campanile Drive, San Diego, CA 92182-7700 USA.
All rights reserved.

visitors since 19-Oct-98