IO Streams - PowerPoint PPT Presentation

1 / 39
About This Presentation
Title:

IO Streams

Description:

are unchecked --they are your fault :-) Virtual machine errors (e.g. OutOfMemoryError) ... For example, Integer.parseInt throws unchecked NumberFormatException ... – PowerPoint PPT presentation

Number of Views:35
Avg rating:3.0/5.0
Slides: 40
Provided by: john1380
Category:

less

Transcript and Presenter's Notes

Title: IO Streams


1
I/O Streams
  • A stream is a sequence of bytes that flow from a
    source to a destination
  • In a program, we read information from an input
    stream and write information to an output stream
  • A program can manage multiple streams at a time
  • The java.io package contains many classes that
    allow us to define various streams with specific
    characteristics

2
I/O Stream Categories
  • The classes in the I/O package divide input and
    output streams into other categories
  • An I/O stream is either a
  • character stream, which deals with text data
  • Use Reader and Writer and their subclasses
  • byte stream, which deal with byte data
  • Use InputStream and OutputStream and their
    subclasses
  • An I/O stream is also either a
  • data stream, which acts as either a source or
    destination
  • processing stream, which alters or manages
    information in the stream

3
Standard I/O
  • There are three standard I/O streams
  • standard input defined by System.in
  • standard output defined by System.out
  • standard error defined by System.err
  • We use System.out when we execute println
    statements
  • System.in is declared to be a generic InputStream
    reference, and therefore usually must be mapped
    to a more useful stream with specific
    characteristics

4
Using JOptionPane
  • Using a GUI dialog box
  • Need to import JOptionPane class from the
    javax.swing library
  • Do not need to create a JoptionPane dialog
  • Use the showInputDialog(prompt) method of the
    JOptionPane class
  • Provide the String prompt to be displayed to the
    user as an argument
  • Returns a String value
  • See InputDemoTest

5
Sample program
  • import javax.swing.JOptionPane // import
    statement
  • class testJOptionPane
  • public static void main(String args)
  • String line JOptionPane.showInputDialog("Enter
    a line of text ")
  • String line2 JOptionPane.showInputDialog("And
    another ")
  • System.out.println(line " " line2)
  • System.out.println()
  • System.out.println("Done...")

6
JOptionPane and numbers
  • If the data values you wish to get from the
    keyboard using JOptionPane are numeric, then an
    extra step is required
  • Convert the String values to the data type the
    value represents
  • Prompt with the following
  • String value JOptionPane.showInputDialog(Enter
    a number)
  • To get an int value
  • int num Integer.parseInt(value)
  • To get a double value
  • double number Double.parseDouble(value)
  • Integer and Double classes (note the
    capitalization) are wrapper classes
  • These have methods that allow us to work with
    numbers as Objects when necessary

7
Input the keyboard
  • Java provides a predefined BufferedInputStream
    object to represent a stream of input that comes
    from the keyboard, System.in
  • Unlike System.out, System.in cannot be used right
    away (different classes)
  • System.in must be used to construct an
    InputStreamReader object
  • Which is used as an argument to construct a
    BufferedReader object
  • Which can then be sent readLine() messages to
    read lines as Strings

8
Getting a line from the keyboard
  • InputStreamReader isr
  • BufferedReader keyBoard
  • String inputLine
  • isr new InputStreamReader(System.in)
  • keyBoard new BufferedReader(isr)
  • inputLine keyBoard.readLine()
  • System.out.print(inputLine)
  • System.out.println("s")

9
Sample program
  • public static void main(String args)
  • throws IOException
  • InputStreamReader isr
  • isr new InputStreamReader(System.in)
  • BufferedReader in new BufferedReader(isr)
  • System.out.print("Enter a phrase )
  • String line in.readLine()
  • System.out.print ("And another ")
  • String line2 in.readLine()
  • System.out.println (line " " line2)
  • System.out.println ()
  • System.out.println ("Done...")

10
Error Codes
  • Traditional approach to error handling method
    returns error code
  • Example JOptionPane.showInputDialog returns null
    if user hits Cancel
  • Problem
  • Calling method may forget to check for error code
  • Calling method may not know how to fix
    error--then it needs to return an error code

11
Exceptions
  • Can't be overlooked
  • Can be handled by a competent handler, not
    necessarily the calling method
  • Throw an exception object to indicate failure
  • if (failure)   XxxException e new
    XxxException(. . .)   throw e
  • More concisely
  • throw new XxxException(. . .)

12
Exceptions
public class BankAccount public void
withdraw(double amount) if (amount
gt balance) throw new
IllegalArgumentException( "Amount exceeds
balance") balance balance - amount
...
13
Hierarchy of Exception Classes
14
Syntax 14.1 Throwing an Exception
  •  throw exceptionObject
  • Example
  •  throw new IllegalArgumentException()
  • Purpose
  • To throw an exception and transfer control to a
    handler for this exception type

15
Checked Exceptions
  • Compiler checks that you are aware of the
    exception
  • Generally used for errors that can happen even
    in correct programs
  • IOException and its sublcasses are checked
    exceptions
  • NullPointerException, ArrayIndexOutOfBoundsExcep
    tion , ... 
  • are unchecked --they are your fault -)
  • Virtual machine errors (e.g. OutOfMemoryError)
    are unchecked
  • Classification not perfect. For example,
    Integer.parseInt throws unchecked
    NumberFormatException
  • Checked exceptions are subclasses of Exception
    that are not subclasses of RuntimeException

16
Checked and Unchecked Exceptions
17
Exception Specifications
  • BufferedReader.readLine() may throw IOException
  • Which is checked
  • Tag calling method with throws IOException
  • public class Coin
  • public void read(BufferedReader in) throws
    IOException
  • value Double.parseDouble(in.readLine())
    name in.readLine()
  • ...

18
Exception Specifications
  • Need to tag caller of Coin.read() as well
  • If fact, depending on the depth of the call in
    your class hierarchy, you need to tag all methods
    on the path to the original source of the checked
    exception
  • At each level, the JVM will check to see if the
    exception is handled
  • If not handled the exception is thrown to the
    next level
  • If there are no handlers in your code, the JVM
    will ultimately handle the exception
  • Can have multiple exception types
  • public void read()    throws IOException,
    ClassNotFoundException

19
Syntax 14.2 Exception Specification
  • accessSpec returnType methodName(parameterType
    parameterName) throws ExceptionClass,
    ExceptionClass . .
  • Example
  •   public void read(BufferedReader in) throws
    IOException
  • Purpose
  • To indicate the checked exceptions that a method
    can throw

20
Reading numbers
  • readLine() reads the information in the stream as
    a String
  • Convert the String values to the data type the
    value represents
  • Get the value from the keyboard
  • String value in.readLine()
  • To get an int value
  • int num Integer.parseInt(value)
  • To get a double value
  • double number Double.parseDouble(value)
  • There are other methods for converting booleans
    and chars
  • Check the API for the wrapper classes Boolean and
    Character

21
Demo Code Reading ints
  • public static void main(String args) throws
    IOException
  • inputStreamReader isr
  • isr new InputStreamReader(System.in)
  • BufferedReader in new BufferedReader(isr)
  • System.out.print("Enter a number )
  • String line in.readLine()
  • System.out.print ("And another ")
  • String line2 in.readLine()
  • int num1 Integer.parseInt(line)
  • int num2 Integer.parseInt(line2)
  • System.out.println (num1 " " num2)
  • System.out.println ()
  • System.out.println ("Done...")

22
Data entry of multiple objects
  • Often we want to work with objects and not with
    the primitive data types
  • We follow one of the two patterns (Count Entry or
    Sentinel Entry), and then do our object
    processing
  • CountEntry get number of data elements and
    process (for loop)
  • Sentinel Entry test for some ending condition
    for the data
  • Provided by the user
  • Intrinsic to the data
  • End of the file
  • Sometimes it is useful to write the code to
    process one object, and when we see it is working
    correctly, we can then build the data entry
    pattern around it.

23
Reading Input Values
  • General pattern
  • boolean done false
  • while (!done) String input read input
    if (end of input indicated) done true
    else process input
  • "Loop and a half
  • See FileInputTestDemo

24
Disk Files
  • Advantages
  • Persistence data in a file lasts longer than
    data on the monitor
  • Capacity more information can be stored on a
    disk than displayed at one time on a monitor
  • Attributes
  • Contents (data)
  • A file name
  • Operations
  • Writing to a file (creating and storing data for
    the first time)
  • Deleting a file
  • Renaming a file
  • Overwriting a file
  • Obtaining contents of a file

25
Modeling disk files
  • Java provides a predefined class to model disk
    files, called File
  • Constructor for the file class
  • Accepts the files name (a String reference) as
    the argument
  • Example
  • File f1 new File(myData.txt)
  • IMPORTANT
  • We have created a reference to a file object
  • This does not create a file on the disk
  • If this file is not on the disk, we cannot do
    anything with this object

26
If the file is on the disk
  • The File object provides two methods that model
    some of the operations we listed earlier
  • delete()
  • File f new File(junk.txt)
  • f.delete()
  • renameTo()
  • File f1, f2
  • f1 new File(junk.txt)
  • f2 new File(garbage.txt)
  • f1.renameTo(f2)

27
Input Disk Files
  • Only slightly more involved that obtaining input
    from a keyboard
  • Instead of BufferedInputStream object
    (System.in), we need a FileInputStream object
  • Construct a FileInputStream object the same as
    constructing a FileOutputStream object
  • File f new File(myData.txt)
  • FileInputStream fs new FileInputStream(f)
  • Now we can use the FileInputStream object as we
    used System.in in getting data from the keyboard

28
Getting a line from a disk file
  • File f new File(myData.txt)
  • FileInputStream fs new FileInputStream(f)
  • InputStreamReader isr
  • BufferedReader input
  • isr new InputStreamReader(fs)
  • input new BufferedReader(isr)
  • String inputLine
  • inputLine input.readLine()
  • System.out.println(inputLine)

29
Writing output to disk
  • To create a new file, or overwrite an existing
    file, we need a pathway, or stream
  • Java has a predefined class to model this stream,
    FileOutputStream
  • The constructor for FileOutputStream uses a
    reference to a File object as its argument
  • File f new File(stuff.txt)
  • FileOutputStream fstream new
    fileOutputStream(f)
  • Opens the file so that it can receive data
  • Creates a new file if the file does not exist
  • However, it does not provide any convenient
    methods for output

30
Using PrintStream methods for disk files
  • We want a PrintStream object to be associated
    with a disk file and not a monitor
  • The PrintStream constructor takes a reference to
    a FileOutputStream as its argument
  • The PrintStream object is associated with the
    FileOutPutStream
  • Using println() and print() methods on this
    PrintStream object means that output will go to
    the disk file
  • File f new File(stuff.txt)
  • FileOutputStream fstream new
    FileOutputStream(f)
  • PrintStream target new PrintStream(fstream)
  • target.println(This is a new disk file.)

31
File Dialogs
  • Use JFileChooser to let a user supply a file name
    through a file dialog
  • Construct a file chooser object
  • Call its showOpenDialog or showSaveDialog method
  • Specify null or the user interface component over
    which to pop up the dialog

32
File Dialogs
  • If the user chooses a fileJFileChooser.APPROVE_O
    PTION is returned
  • If the user cancels the selectionJFileChooser.CA
    NCEL_OPTION is returned
  • If a file is chosen, use GetSelectedFile method
    to obtain a File object describing the file

33
A JFileChooser Dialog
34
Code to Use a JFileChooser
  • JFileChooser chooser new JFileChooser()
  • FileReader in null
  • if (chooser.showOpenDialog(null)
    JFileChooser.APPROVE_OPTION)
  • File selectedFile chooser.getSelected
    File()
  • in new FileReader(selectedFile)

35
Object Serialization
  • Object serialization is the act of saving an
    object, and its current state, so that it can be
    used again in another program
  • The idea that an object can live beyond the
    program that created it is called persistence
  • Object serialization is accomplished using the
    classes ObjectOutputStream and ObjectInputStream
  • Serialization takes into account any other
    objects that are referenced by an object being
    serialized, saving them too

36
Object Streams
  • Objects are saved in binary format hence, you
    use streams
  • ObjectOutputStream class can save entire objects
    to disk
  • ObjectInputStream class can read objects back in
    from disk
  • Writing a Coin object to a file
  • Coin c ...
  • ObjectOutputStream out new ObjectOutputStream(ne
    w FileOutputStream("coins.dat"))
  • out.writeObject(c)
  • Reading a Coin object from a file
  • ObjectInputStream in new ObjectInputStream(new
  • FileInputStream("coins
    .dat"))
  • Coin c (Coin)in.readObject()

37
The StringTokenizer Class
  • The next example makes use of the StringTokenizer
    class, which is defined in the java.util package
  • Must have import java.util. at top of source
    file
  • A StringTokenizer object separates a string into
    smaller substrings (tokens)
  • By default, the tokenizer separates the string at
    white space
  • The StringTokenizer constructor takes the
    original string to be separated as a parameter
  • Each call to the nextToken method returns the
    next token in the string

38
StringTokenizer class methods
  • StringTokenizer(String str)           Constructs
    a string tokenizer for the specified string.
  • int countTokens()
  • Returns the number of tokens in a StringTokenizer
    object
  • boolean hasMoreTokens()
  • Tests if there are more tokens available from
    this tokenizer's string.
  • boolean hasMoreElements()
  • Returns the same value as the hasMoreTokens
    method.
  • String nextToken()
  • Returns the next token from this string
    tokenizer.
  • Object nextElement()
  • Returns the same value as the nextToken method,
    except that its declared return value is Object
    rather than String.

39
Using the String Tokenizer
  • BufferedReader io new BufferedReader(new
    InputStreamReader(System.in))
  • System.out.print(Enter a series of numbers )
  • String entry io.readLine()
  • StringTokenizer strk new StringTokenizer(entry)
  • int total 0
  • while (strk.hasMoreTokens())
  • String temp strk.nextToken()
  • int value Integer.parseInt(temp)
  • total value
  • System.out.println(The total of the numbers
    entered total)
Write a Comment
User Comments (0)
About PowerShow.com