copyright © 1999 - 2012 curt hill java i/o flexibility and layering

40
Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Upload: dina-nelson

Post on 02-Jan-2016

216 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Java I/OFlexibility and Layering

Page 2: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

The Difficulty of File Design• There are very many different

approaches to file design in programming languages

• None have mastered it or all others would have copied them

• C++ has two completely different approaches– IOStream use << and >>– StdIO use printf and scanf

• Random access files are particularly operating system sensitive

Page 3: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

One example: end of file• Three or more approaches• Error exit routine

– FORTRAN– COBOL

• Pre-check– Pascal

• Post-check– C++

Page 4: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

External Data• What does data come from? or

Where does it go?– A file, such as on disk– Console– Network connection– Pipe– String– Array of bytes– Two or more of above collected

together• The problem is making these look

similar

Page 5: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Formatting• How is the data modified from source to

destination?• No formatting

– Raw bytes or characters• Collecting

– An integer stored as 4 binary bytes

• Formatting based on desired type– Digit characters transformed into an integer

Page 6: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Direction•Files may be processed in several directions–Input–Output

•Append

–Input and Output

Page 7: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Organization and Access• Organization

– Sequential• May be buffered for efficiency

– Random Access• Direct• Indexed

• Access– How it is processed– Must be no stronger than organization

• All are OS dependent

Page 8: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Classes• There are many classes that capture

these capabilities• They are then cascaded to give the

desired result• The beginnings are InputStream and

OutputStream which are abstract base classes

• To be useful they are subclassed• These are in java.io.*

Page 9: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

InputStream• Defines the following functions:

– int available()– void close()– void mark(int)– boolean marksupported()– int read(byte [])– int read(byte [], int offset, int len)– void reset()– long skip(long)

Page 10: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

InputStream Descendents• AudioInputStream • ByteArrayInputStream• FileInputStream

– Constructor takes a file name string

• FilterInputStream• ObjectInputStream• PipedInputStream• SequenceInputStream• StringBufferInputStream• There are also other abstract classes

Page 11: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

The Readers• The InputStream descendents do

not have the convenient methods for processing input that is people readable

• The read methods generally only reads a byte– This is one half of a character

• There are several Reader objects that do have nicer methods

Copyright © 1999 - 2012 Curt Hill

Page 12: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Reader• This is generally not used, but is

the ancestor of several that are quite handy

• The read method of this object (and descendents) reads a character, not a byte

• It has several handy descendents:– InputStreamReader– BufferedReader

Copyright © 1999 - 2012 Curt Hill

Page 13: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Readers• InputStreamReader adds the

functionality of reading from an InputStream– Such as a disk file

• BufferedReader adds two things:– Buffering – readLine method that reads a whole

line and returns a string

Copyright © 1999 - 2012 Curt Hill

Page 14: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

End of File• Each class has the option to handle

EOF differently• The DataInputStream does throw

an EOFException• InputStreamReader has a read

which returns an int– If EOF it returns a -1

• It also has a ready method which returns true should there be somthing left to read

Page 15: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

OutputStream• Another abstract base class• Defines the following functions:

– void close()– void flush()– void write(byte [])– void write(byte [], int offset, int len)

Page 16: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Instantiable Output Streams

• ByteArrayOutputStream• FileOutputStream• PipeOutputStream• FilterOutputStream

Page 17: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Exceptions• InputStream and OutputStream objects

throw various kinds of IOExceptions• Constructors using file names usually

throw FileNotFoundException• Others I/O throw IOException• Most operations need to be in try catch

Page 18: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Filters• FilterInputStream and

FilterOutputStream are also abstract classes

• Designed to be the super classes of all formatting classes or any other added functionality

• Subclasses include: BufferXXXStream, DataXXXStream and others

• Provide the same functionality as InputStreams or OutputStreams

Page 19: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Buffering• Buffering separates logical reads

or writes from physical reads or writes

• Devised in the 1950s to save space on tape

• Today we do it to make access faster

• Reading an entire track is only slightly slower than reading a single sector

Page 20: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Java Buffered Classes• Two buffering classes:

– BufferedInputStream which takes an InputStream in its constructor

– BufferedOutputStream which takes an OutputStream in its constructor

• They provide all the same functionality as Stream but add buffering

Page 21: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Output formatting

• PrintStream is a subclass of FilterOutputStream

• Constructor takes an OutputStream• Offers the print and println functions with

many overloads– All the primitives– Object (uses String.valueOf)– String

• Handles its own exceptions so try catch is only needed for Opening

Page 22: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

print and println

• These are methods which are defined in PrintStream

• They format variables and output them

• They are overloaded to take several different kinds of arguments

• They will only take one argument each– println may have no arguments as well

Page 23: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

How the Classes Fit

P

OutputStream

ApplicationPrintStream

BufferedOutputStream

Page 24: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Example Code• import java.io.*;• PrintStream f;• try { f = new PrintStream( new BufferedOutputStream( new FileOutputStream( "junk.out"))); } catch (FileNotFoundException e) {error stuff};

• f.print("Double "); f.println(d);

Page 25: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Discussion• Only the creation needs to be

protected by try catch• PrintStream handles all the errors

of writing itself• The print and println methods are

similar to those used by System.out

Page 26: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

PrintWriter

• Similar to PrintStream– Not derived from PrintStream– All the same methods

• Constructor takes an OutputStream

• checkError returns whether an error occurred

Page 27: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Console Redirection• The JVM has three standard files

like C– Standard output

• System.out

– Standard error• System.err

– Standard input• System.in

• Each of these may be redirected to a file or processed by a program

Page 28: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Redirection• Usually done for the execution of

an existing program• Three steps

– Start program– Redirect files– Process these files

Page 29: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Starting a program• Uses the Runtime static object Runtime rt = Runtime.getRuntime();

• Now start the programProcess proc = rt.exec(cmd,environment,dir);

• Cmd is an array of string• Environment is an array of strings• Dir is string

Page 30: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Standard files of a process

• Use a process method to get the output file

• Three Process methods are:– OutputStream getOutputStream();

• Connects to input

– InputStream getErrorStream();• Connects to error

– InputStream getInputStream();• Connects to output

Page 31: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Capture the file• Use this as file:

PrintWriter ps = newPrintWriter(proc.getOutputStream());

• Any println to this file is piped to the process input file

Page 32: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

File output• PrintStream is for people readable text• What if the data is to be written to a

file and then later read back in?• No formatting is needed, instead

writing in binary• Yet it must be reversible and machine

independent• Uses DataOutputStream

Page 33: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

DataOutputStream

• Subclass of FilterInputStream• Constructor takes an OutputStream• New functions are:

– void writeFloat(float)– void writeInt(int)– void writeBytes(String) – void writeChars(String)

• There is no writeString

Page 34: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Input formatting• DataInputStream is a subclass of

FilterInputStream• Reads in what a

DataOutputStream wrote• Constructor takes an InputStream• Provides functions for reading the

various types:– byte readByte()– double readDouble()

• No read string

Page 35: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

What about conversion?• Converting a string of characters into

an integer has mostly been left out of tradional Java Readers and Streams

• The way to do this is:– Read whole lines– Chop into pieces based on white space– Use Integer.parseInt (or similar) to

convert to needed types

• In Java 5 the Scanner object was introduced

Copyright © 1999 - 2012 Curt Hill

Page 36: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Scanner• A Scanner may be constructed

using either a File or InputStream– A File may be obtained from

JFileChooser

• The scanner by default uses whitespace as the delimiter between tokens

• It has a series of hasNextXXX and nextXXX methods

Copyright © 1999 - 2012 Curt Hill

Page 37: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

hasNext methods• Returns a boolean • True if the item is the next token• So:hasNextInt()is true if the next token can be interpreted as an integer

• Most of the types have one:– hasNextDouble– hasNextFloat– hasNextLine

Copyright © 1999 - 2012 Curt Hill

Page 38: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

next Methods• Reads and returns the next item• Example:int j = sc.nextInt();

• One for most types:– nextBoolean– nextDouble– nextLine

Copyright © 1999 - 2012 Curt Hill

Page 39: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Scanner Exceptions• The hasNextXXX will throw the

IllegalStateException if the scanner is closed

• The nextXXX will throw:– InputMismatchException if the item

does not conform to specifications– NoSuchElementException if the

Scanner has no input left– IllegalStateException if the scanner is

closed

Copyright © 1999 - 2012 Curt Hill

Page 40: Copyright © 1999 - 2012 Curt Hill Java I/O Flexibility and Layering

Copyright © 1999 - 2012 Curt Hill

Text files• Text files in any Microsoft

Operating System always end a line with two characters– A carriage return followed by a line

feed– Both are control characters

• UNIX based systems use only a line feed

• This may change how the file is processed on different systems