IO Streams - PowerPoint PPT Presentation

1 / 30
About This Presentation
Title:

IO Streams

Description:

In a program, we read data from an input stream and write information to an output stream ... catch (IOException e) { e.printStackTrace(); Writing to a Text File ... – PowerPoint PPT presentation

Number of Views:95
Avg rating:3.0/5.0
Slides: 31
Provided by: phil168
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 data 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
  • byte stream, which deal with byte data
  • An I/O stream is also either a
  • data stream, which acts as either a source or
    destination
  • processing stream, which alters or manages data
    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
The Keyboard Class
  • The Keyboard class was written to facilitate
    reading data from standard input
  • Now we can examine the processing of the Keyboard
    class in more detail
  • The Keyboard class
  • declares a useful standard input stream
  • handles exceptions that may be thrown
  • parses input lines into separate values
  • converts input stings into the expected type
  • handles conversion problems

5
The Standard Input Stream
  • The Keyboard class declares the following input
    stream
  • InputStreamReader isr
  • new InputStreamReader (System.in)
  • BufferedReader stdin new BufferedReader (isr)
  • The InputStreamReader object converts the
    original byte stream into a character stream
  • The BufferedReader object allows us to use the
    readLine method to get an entire line of input

6
Text Files
  • To write data to a text file we need to create an
    object of class PrintWriter. The class includes
    two methods print and println
  • To read data from a text file, we need to create
    two objects, one of class FileReader, and the
    other object of class BufferedReader.

7
Input Text Files
  • Data can be read from and written to text files
    by declaring and using the correct I/O streams
  • The FileReader class represents an input file
    containing character data
  • To create an object of this class we need to pass
    the name of the input text file as argument
  • FileReader infile new FileReader
    (myfile.data)

8
Method with Input Text File
  • Import java.io.
  • public class Ioerror
  • public static void main (String args)
  • try
  • FileReader ff new FileReader
    (indata.txt)
  • catch (IOException e)
  • e.printStackTrace()
  • // end main
  • // end class

9
Reading Lines and Fields
  • Reading one character at a time from an I/O
    device is very inefficient
  • Normally an entire block of data is read at a
    time (1024 bytes) storing in a buffer
  • Class BufferedReader is used for Buffered
    reading
  • FileReader infile new FileReader
    (myfile.data)
  • BufferedReader bbin BufferedReader(infile)
  • This allows reading a block of data into a buffer

10
Reading Data into a Buffer
  • Import java.io.
  • public class Ioerror
  • public static void main (String args)
  • String line
  • try
  • FileReader ff new FileReader
    (indata.txt)
  • BufferedReader fbuf new BufferedReader
    (ff)
  • while (line fbuf.readLine()) ! null) //
    read until EOF
  • System.out.println(line)
  • fbuf.close()
  • catch (IOException e)
  • e.printStackTrace()

11
Separating Fields
  • public static void main (String args)
  • String line, street, city, state, zip
  • StringTokenizer fields
  • Address taddress
  • try
  • FileReader ff new FileReader
    (indata.txt)
  • BufferedReader fbuf new BufferedReader
    (ff)
  • while (line fbuf.readLine()) ! null)
  • System.out.println(line)
  • fields new StringTokenizer (line, )
  • if (fields.countTokens() 4)
  • street fields.nextToken()
  • city fields.nextToken()
  • state fields.nextToken()
  • zip fields.nextToken()
  • taddress new Address (street, city, state,
    zip)
  • System.out.println(taddress)
  • // end while

12
Writing to a Text File
  • We first create an object of class FileWriter
    passing the name of the external file as argument
  • Create a PrintWriter object passing the previous
    object as an argument
  • FileWriter outf new FileWriter (myoutf.txt)
  • PrintWriter p new PrintWriter (outf, true)

13
Writing Data to a Text File
  • In a loop
  • p.write(item )
  • p.writeln(y)
  • After the loop
  • p.close()

14
Binary File Manipulation
  • To open a file, we create a File object, to
    associate it to the file
  • File mydatafile new File (mydat1.data)
  • if (mydatafile.isFile)
  • System.out.println(File Ok)
  • else
  • System.out.println(Its a directory)

15
Read/Write File Operations
  • For R/W file operations, we need to open an input
    stream and an output stream objects
  • Two such Java streams are FileInputstream and
    FileOutputStream
  • To attach streams to files ofile and ifile
  • FileOutputStream ostr
  • FileInputStream istr
  • ostr new FileOutputStream (ofile)
  • istr new FileInputStream(ifile)

16
Data To and From a Stream
  • Data is written directly to an output stream,
    which has been attached to a file
  • ostr.write(myarray) // write byte array
  • . . .
  • ostr.close()
  • Data is read from an input stream, which has been
    attached to a file
  • istr.read(yarray)
  • istr.close()

17
High-Level File Operations
  • To facilitate the conversion of primitive data
    types
  • A Datastream object is a layer on top of a
    FileStream object
  • To create a DataOutputStream object, we first
    create a file object then a FileOutputStream
    object

18
Writing Values of Primitive Types
  • To write an integer and a float value to a file
  • File ofile new File (myofile.dat)
  • FileOutputStream ostr
  • ostr new FileOutputStream (ofile)
  • DataOutputStream dostr
  • dostr new DataOutputStream (dostr)
  • dostr.writeInt (87) // an integer
    value
  • dostr.writeFloat(1123.5F) // a float value

19
Reading Values of Primitive Types
  • To read an integer and a float values from the
    file
  • File ifile new File (myofile.dat)
  • FileInputStream istr int intval float floatval
  • istr new FileInputStream (ifile)
  • DataInputStream distr
  • distr new DataInputStream (istr)
  • distr.readInt (intval) // an integer
    value
  • distr.readFloat(floatval) // a float value

20
Writing to a Textfile
File tfile new File (otfile.dat) FileOutputSt
ream ostr ostr new FileOutputStream
(tfile) PrintWriter postr postr new
PrintWriter (ostr) dostr.println (87)
// an integer value dostr.println(1123.5F) // a
float value dostr.close() //
close file
21
Reading From a Textfile
  • File ifile new File (otfile.dat)
  • FileReader fhr new FileReader (ifile)
  • BufferedReader bufr
  • bufr new BufferedReader (fhr)
  • // Read text data
  • String tdata bufr.readline()
  • // the string data may need to be converted to
    their primitive types (use a wrapper object)

22
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

23
Object Serialization
  • The process of converting an object into a
    representation of 8-bits units.
  • It is the key to providing object persistency,
    the ability to save an objects state across
    program invocation.
  • This concept is essential in all network
    programming.

24
Object Persistency
  • A serialized object can be stored in an 8-bit
    form (I.e., on a file), and read back and
    restored to its exact representation.
  • Internal state of the object must be restored
  • Internal references must also be restored.
  • Classes ObjectOutputStream and ObjectInputStream
    and the Serialization interface hide most of
    these details.

25
Object I/O in Java
  • Objects can be stored directly to a file
  • Two streams are used
  • ObjectInputStream to read objects from a file
  • ObjectOutputStream to write objects to a file.
  • For object I/O, the interface Serializable must
    be implemented in the class that defines the
    object

26
Using Serializable
  • Consider an object of class Sched is to read or
    stored on a file.
  • import java.io.
  • class Sched implements Serializable
  • // class members

27
Reading Objects from a File
  • Carry out the following steps
  • Declare and create a File object
  • Declare and create a FileInputStream object
  • Declare and create an ObjectInputStream object
  • Invoke the readObject() method of the
    ObjectInputStream object
  • Cast the input object to the appropriate object
    type

28
Example of Reading Object
  • File myfile new File (myobj.dat)
  • FileInputStream myistream
  • myistream new FileInputStream (myfile)
  • ObjectInputStream myobjstr
  • myobjstr new ObjectInputStream (myistream)
  • Sched mysched // object to read
  • mysched (Sched) myobjstr.readObject()

29
Writing Objects to a File
  • To write an object carry out the following steps
  • Declare and create a File object
  • Declare and create a FileOutputStream object
  • Declare and create an ObjectOutputStream object
  • Invoke the writeObject() method of the
    ObjectOutputStream object

30
Example of Writing an Object
  • File myfile new File (myobj.dat)
  • FileOutputStream myostream
  • myostream new FileOutputStream (myfile)
  • ObjectOutputStream myobjstr
  • myobjstr
  • new ObjectOutputStream (myostream)
  • Sched mysched new Sched()
  • myobjstr.writeObject (mysched)
Write a Comment
User Comments (0)
About PowerShow.com