CS 596 Java Programming Fall Semester, 1998 Java IO part 2 |
||
---|---|---|
© 1998, All Rights Reserved, SDSU & Roger Whitney San Diego State University -- This page last updated 21-Dec-98 |
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)
File Info
A file is specified by a pathname, either
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
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(); } }
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
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 ); } }
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
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
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; } }
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:
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
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
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
//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() )); } }
//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
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
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) |
nextToken
Returns the type of the next token
Places token type in field ttype
Places the token in a public field
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
Terms and Defaults Special Characters
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.
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
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
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
\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
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
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