itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

download itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

of 268

Transcript of itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    1/268

    Chapter 19

    Binary Input & OutputJava I ITP 120

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    2/268

    ITP 120 Java Programming I2

    Patrick Healy

    Class #15 Input and OutputChapter Objectives

    To understand how I/O is handled in Java

    To distinguish between text I/O and binary I/O

    To read and write bytes using FileInputStream and FileOutputStream

    To read and write primitive values and strings using the DataInputStream and

    DataOutputStream classes

    To store and restore objects using ObjectOutputStream and ObjectInputStream, and

    to understand how objects are serialized and what kind of objects can be serialized

    To use the Serializable interface to enable objects to be serializable (optional)

    To know how to serialize arrays (optional)

    To use RandomAccessFile for both read and write (Optional).

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    3/268

    ITP 120 Java Programming I3

    Patrick Healy

    Class #15 Input and Output

    Overview

    The java.io.*package provides a library of classes to read and writevarious types of data.

    In Java, all data I/O is handled in the form of streams

    Data streams can be byte streams or character streams

    The java.io package has classes that process byte streams of all types

    NOTE: In Java, a character is 2 BYTES !

    Also NOTE: a Unicode character is 2 bytes !

    The Reader and Writer classes process character streams.

    Streams can be layered, so that one type of streams can be convertedto another type of streams by chaining. Chaining a character stream

    reader to a byte stream reader to read bytes on one end and producecharacters at the other end .

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    4/268

    ITP 120 Java Programming I4

    Patrick Healy

    Class #15 Input and Output

    Overview --- Streams

    A stream is an abstraction of a continuous one-way flow of data.

    Program

    Output Stream

    File

    Input Stream

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    5/268ITP 120 Java Programming I5

    Patrick Healy

    Class #15 Input and Output

    2 Types of Stream Classes: Bytes & Characters

    The stream classes can be categorized into two types: byte streams and

    character streams.

    The InputStream/OutputStreamclass is the

    root of all BYTEstream classes

    The Reader/Writer class is the root of all CHARACTERstream

    classes.

    The subclasses ofInputStream/OutputStreamare analogous to thesubclasses ofReader/Writer.

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    6/268ITP 120 Java Programming I6

    Patrick Healy

    Class #15 Input and Output

    Byte Stream Classes (note: the word stream )

    InputStream

    OutputStream

    RandomAccessFile

    Object

    PipeOutputStream

    SequenceInputStream

    StringBufferInputStream

    ByteArrayOutputStream

    ObjectOutputStream

    FilterOutputStream

    FileOutputStream

    PipedInputStream

    PushBackInputStream

    BufferedInputStream

    LineNumberInputStream

    DataInputStream

    BufferedOutputStream

    DataOutputStream

    PrintStream

    ObjectInputStream

    FilterInputStream

    FileInputStream

    ByteArrayInputStreamInputData

    OutputData

    ObjectOutput

    ObjectInput

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    7/268ITP 120 Java Programming I7

    Patrick Healy

    Class #15 Input and OutputCharacter Stream Classes (Character = 2 bytes)

    Reader

    Writer

    StreamTokenizer

    Object

    PrintWriter

    BufferedWriter

    CharArrayWriter

    PipedWriter

    FilterWriter

    PipedReader

    LineNumberReader

    FileReader

    PushBackReader

    FileWriter

    StringWriter

    StringReader

    InputStreamReader

    CharArrayReader

    BufferedReader

    FilterReader

    OutputStreamWriter

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    8/268

    How is I/O Handled in Java?A File object encapsulates the properties of a file or a path, but does not contain

    the methods for reading/writing data from/to a file. In order to perform I/O, youneed to create objects using appropriate Java I/O classes.

    Formatter output = new Formatter("temp.txt");

    output.format("%s", "Java 101");

    output.close();

    Scanner input = new Scanner(new File("temp.txt"));

    System.out.println(input.nextLine());

    Program

    Input object

    created from an

    input class

    Output object

    created from an

    output class

    Input stream

    Output stream

    File

    File010111001

    110011011

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    9/268

    Text Files vs. Binary Files Data stored in a text file are represented in human-readable form.

    Data stored in a binary file are represented in binary form. You

    cannot read binary files. Binary files are designed to be read byprograms. For example, the Java source programs are stored in textfiles and can be read by a text editor, but the Java classes are stored inbinary files and are read by the JVM. The advantage of binary files isthat they are more efficient to process than text files.

    Although it is not technically precise and correct, you can imaginethat a text file consists of a sequence of characters and a binary fileconsists of a sequence of bits. For example, the decimal integer 199 isstored as the sequence of three characters: '1', '9', '9' in a text file andthe same integer is stored as a byte-type value C7 in a binary file,because decimal 199 equals to hex C7.

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    10/268

    Binary I/O

    Text I/O requires encoding and decoding. The JVM converts a Unicode

    to a file specific encoding when writing a character and coverts a filespecific encoding to a Unicode when reading a character. Binary I/O

    does not require conversions. When you write a byte to a file, the original

    byte is copied into the file. When you read a byte from a file, the exact

    byte in the file is returned.

    Text I/O program

    The Unicode of

    the characterEncoding/

    Decoding

    Binary I/O program

    A byte is read/written(b)

    (a)

    e.g.

    "199"

    The encoding of the characteris stored in the file

    0x31

    e.g.

    199 00110111

    00110001 00111001 00111001

    0x39 0x39

    0xC7

    The same byte in the file

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    11/268

    Binary I/O Classes

    InputStream

    OutputStream

    Object

    ObjectOutputStream

    FilterOutputStream

    FileOutputStream

    BufferedInputStream

    DataInputStream

    BufferedOutputStream

    DataOutputStream

    PrintStream

    ObjectInputStream

    FilterInputStream

    FileInputStream

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    12/268

    java.io.InputStream

    +read(): int

    +read(b: byte[]): int

    +read(b: byte[], off: int,

    len: int): int

    +available(): int

    +close(): void

    +skip(n: long): long

    +markSupported(): boolean

    +mark(readlimit: int): void

    +reset(): void

    Reads the next byte of data from the input stream. The value byte is returned as

    an int value in the range 0 to 255. If no byte is available because the end of

    the stream has been reached, the value1 is returned.

    Reads up to b.length bytes into array b from the input stream and returns the

    actual number of bytes read. Returns -1 at the end of the stream.

    Reads bytes from the input stream and stores into b[off], b[off+1], ,

    b[off+len-1]. The actual number of bytes read is returned. Returns -1 at theend of the stream.

    Returns the number of bytes that can be read from the input stream.

    Closes this input stream and releases any system resources associated with the

    stream.

    Skips over and discards n bytes of data from this input stream. The actualnumber of bytes skipped is returned.

    Tests if this input stream supports the mark and reset methods.

    Marks the current position in this input stream.

    Repositions this stream to the position at the time the mark method was last

    called on this input stream.

    The value returned is a byte as an

    int type.

    InputStream

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    13/268

    The value is a byte as an int type.

    OutputStream

    java.io.OutputStream

    +write(int b): void

    +write(b: byte[]): void

    +write(b: byte[], off: int,

    len: int): void

    +close(): void

    +flush(): void

    Writes the specified byte to this output stream. The parameter b is an int value.(byte)b is written to the output stream.

    Writes all the bytes in array b to the output stream.

    Writes b[off], b[off+1], , b[off+len-1] into the output stream.

    Closes this input stream and releases any system resources associated with thestream.

    Flushes this output stream and forces any buffered output bytes to be written out.

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    14/268

    FileInputStream/FileOutputStream

    FileInputStream/FileOutputStream

    associates a binary input/outputstream with an external file. All themethods inFileInputStream/FileOuptputStrea

    InputStream

    OutputStream

    Object

    ObjectOutputStream

    FilterOutputStream

    FileOutputStream

    BufferedInputStream

    DataInputStream

    BufferedOutputStream

    DataOutputStream

    PrintStream

    ObjectInputStream

    FilterInputStream

    FileInputStream

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    15/268

    FileInputStream

    To construct a FileInputStream, use the following constructors:

    public FileInputStream(String filename)

    public FileInputStream(File file)

    A java.io.FileNotFoundException would occur if you attemptto create a FileInputStream with a nonexistent file.

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    16/268

    FileOutputStream

    To construct a FileOutputStream, use the following

    constructors:

    public FileOutputStream(String filename)

    public FileOutputStream(File file)

    public FileOutputStream(String filename, boolean append)

    public FileOutputStream(File file, boolean append)

    If the file does not exist, a new file would be created. If

    the file already exists, the first two constructors woulddelete the current contents in the file. To retain thecurrent content and append new data into the file, use thelast two constructors by passing true to the append

    TestFileStream Run

    http://localhost/var/www/apps/conversion/tmp/scratch_6/html/TestFileStream.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_6/html/TestFileStream.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_6/html/TestFileStream.html
  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    17/268

    FilterInputStream/FilterOutputStream

    Filter streams are streams that filter bytes for some purpose. The basic byte input streamprovides a read method that can only be used for reading bytes. If you want to read integers,

    doubles, or strings, you need a filter class to wrap the byte input stream. Using a filter classenables you to read integers, doubles, and strings instead of bytes and characters.FilterInputStream and FilterOutputStream are the base classes for filtering data. When youneed to process primitive numeric types, use DatInputStream and DataOutputStream to filterbytes.

    InputStream

    OutputStream

    Object

    ObjectOutputStream

    FilterOutputStream

    FileOutputStream

    BufferedInputStream

    DataInputStream

    BufferedOutputStream

    DataOutputStream

    PrintStream

    ObjectInputStream

    FilterInputStream

    FileInputStream

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    18/268

    DataInputStream/DataOutputStreamDataInputStream reads bytes from the stream andconverts them into appropriate primitive type valuesor strings.

    InputStream

    OutputStream

    Object

    ObjectOutputStream

    FilterOutputStream

    FileOutputStream

    BufferedInputStream

    DataInputStream

    BufferedOutputStream

    DataOutputStream

    PrintStream

    ObjectInputStream

    FilterInputStream

    FileInputStream

    DataOutputStream converts primitive type values or

    strings into bytes and output the bytes to the stream.

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    19/268

    DataInputStream

    DataInputStream extends FilterInputStream and

    implements the DataInput interface.

    java.io.DataInput

    +readBoolean(): boolean

    +readByte(): byte

    +readChar(): char

    +readFloat(): float

    +readDouble(): float

    +readInt(): int

    +readLong(): long

    +readShort(): short+readLine(): String

    +readUTF(): String

    Reads a Boolean from the input stream.

    Reads a byte from the input stream.

    Reads a character from the input stream.

    Reads a float from the input stream.

    Reads a double from the input stream.

    Reads an int from the input stream.

    Reads a long from the input stream.

    Reads a short from the input stream.Reads a line of characters from input.

    Reads a string in UTF format.

    InputStream

    FilterInputStream

    DataInputStream

    +DataInputStream(

    in: InputStream)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    20/268

    DataOutputStreamDataOutputStream extends FilterOutputStream and implements the

    DataOutput interface.

    java.io.DataOutput

    +writeBoolean(b: Boolean): void

    +writeByte(v: int): void

    +writeBytes(s: String): void

    +writeChar(c: char): void

    +writeChars(s: String): void

    +writeFloat(v: float): void

    +writeDouble(v: float): void

    +writeInt(v: int): void

    +writeLong(v: long): void+writeShort(v: short): void

    +writeUTF(s: String): void

    Writes a Boolean to the output stream.

    Writes to the output stream the eight low-order bits

    of the argument v.

    Writes the lower byte of the characters in a string to

    the output stream.

    Writes a character (composed of two bytes) to theoutput stream.

    Writes every character in the string s, to the output

    stream, in order, two bytes per character.

    Writes a float value to the output stream.

    Writes a double value to the output stream.

    Writes an int value to the output stream.

    Writes a long value to the output stream.Writes a short value to the output stream.

    Writes two bytes of length information to the output

    stream, followed by the UTF representation of

    every character in the string s.

    OutputStream

    FilterOutputStream

    DataOutputStream

    +DataOutputStream(

    out: OutputStream)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    21/268

    Characters and Strings in Binary I/O

    A Unicode consists of two bytes. The writeChar(char c)

    method writes the Unicode of character c to the output.The writeChars(String s) method writes the Unicode foreach character in the string s to the output.Why UTF-8? What is UTF-8?

    UTF-8 is a coding scheme that allows systems to operate with both ASCIIand Unicode efficiently. Most operating systems use ASCII. Java usesUnicode. The ASCII character set is a subset of the Unicode character set.Since most applications need only the ASCII character set, it is a waste torepresent an 8-bit ASCII character as a 16-bit Unicode character. The UTF-

    8 is an alternative scheme that stores a character using 1, 2, or 3 bytes.ASCII values (less than 0x7F) are coded in one byte. Unicode values lessthan 0x7FF are coded in two bytes. Other Unicode values are coded inthree bytes.

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    22/268

    Using DataInputStream/DataOutputStream

    Data streams are used as wrappers on existing input and

    output streams to filter data in the original stream. Theyare created using the following constructors:

    public DataInputStream(InputStream instream)

    public DataOutputStream(OutputStream outstream)

    The statements given below create data streams. The firststatement creates an input stream for file in.dat; thesecond statement creates an output stream for file

    out.dat.DataInputStream infile =

    new DataInputStream(new FileInputStream("in.dat"));

    DataOutputStream outfile =

    new DataOut utStream new FileOut utStream "out.dat"

    TestDataStream Run

    http://localhost/var/www/apps/conversion/tmp/scratch_6/html/TestDataStream.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_6/html/TestDataStream.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_6/html/TestDataStream.html
  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    23/268

    Checking End of File

    TIP: If you keep reading data at the end of a stream, anEOFException would occur. So how do you check the

    end of a file? You can use input.available() to check it.input.available() == 0 indicates that it is the end of a file.

    Order and Format

    CAUTION: You have to read the data in the same order and same format inwhich they are stored. For example, since names are written in UTF-8 usingwriteUTF, you must read names using readUTF.

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    24/268

    BufferedInputStream/

    BufferedOutputStreamUsing buffers to speed up I/O

    InputStream

    OutputStream

    Object

    ObjectOutputStream

    FilterOutputStream

    FileOutputStream

    BufferedInputStream

    DataInputStream

    BufferedOutputStream

    DataOutputStream

    PrintStream

    ObjectInputStream

    FilterInputStream

    FileInputStream

    BufferedInputStream/BufferedOutputStream does not contain new methods. All

    the methods BufferedInputStream/BufferedOutputStream are inherited from the

    InputStream/OutputStream classes.

    Constructing

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    25/268

    Constructing

    BufferedInputStream/BufferedOutputStream

    // Create a BufferedInputStreampublic BufferedInputStream(InputStream in)

    public BufferedInputStream(InputStream in, int bufferSize)

    // Create a BufferedOutputStream

    public BufferedOutputStream(OutputStream out)

    public BufferedOutputStream(OutputStreamr out, int

    bufferSize)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    26/268

    Case Studies: Copy File

    This case study develops a program that copies files. The user

    needs to provide a source file and a target file as command-linearguments using the following command:

    java Copy source target

    The program copies a source file to a target file and displays thenumber of bytes in the file. If the source does not exist, tell theuser the file is not found. If the target file already exists, tell theuser the file already exists. Copy Run

    Obj t I/O

    Optional

    http://localhost/var/www/apps/conversion/tmp/scratch_6/html/Copy.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_6/html/Copy.html
  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    27/268

    Object I/O

    DataInputStream/DataOutputStream enables you to perform I/O for

    primitive type values and strings. ObjectInputStream/ObjectOutputStreamenables you to perform I/O for objects in addition for primitive typevalues and strings.

    InputStream

    OutputStream

    Object

    ObjectOutputStream

    FilterOutputStream

    FileOutputStream

    BufferedInputStream

    DataInputStream

    BufferedOutputStream

    DataOutputStream

    PrintStream

    ObjectInputStream

    FilterInputStream

    FileInputStream

    p

    Obj tI tSt

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    28/268

    ObjectInputStream

    ObjectInputStream extends InputStream and implementsObjectInput and ObjectStreamConstants.

    java.io.ObjectInput

    +readObject(): Object Reads an object.

    java.io.InputStream

    java.io.ObjectInputStream

    +ObjectInputStream(in: InputStream)

    java.io.DataInput

    ObjectStreamConstants

    Obj tO t tSt

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    29/268

    ObjectOutputStream

    ObjectOutputStream extends OutputStream and implementsObjectOutput and ObjectStreamConstants.

    java.io.ObjectOutput

    +writeObject(o: Object): void Writes an object.

    ava.io.OutputStream

    java.io.ObjectOutputStream

    +ObjectOutputStream(out: OutputStream)

    java.io.DataOutput

    ObjectStreamConstants

    U i Obj t St

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    30/268

    Using Object Streams

    You may wrap an

    ObjectInputStream/ObjectOutputStream on anyInputStream/OutputStream using the following

    constructors:

    // Create an ObjectInputStream

    public ObjectInputStream(InputStream in)

    // Create an ObjectOutputStream

    public ObjectOutputStream(OutputStream out)

    TestObjectOutputStream Run

    TestObjectInputStream Run

    Random Access Files

    http://localhost/var/www/apps/conversion/tmp/scratch_6/html/TestObjectOutputStream.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_6/html/TestObjectInputStream.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_6/html/TestObjectInputStream.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_6/html/TestObjectOutputStream.html
  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    31/268

    Random Access Files

    All of the streams you have used so far are known as read-

    only or write-only streams. The external files of these streamsare sequential files that cannot be updated without creating anew file. It is often necessary to modify files or to insert newrecords into files. Java provides the RandomAccessFile classto allow a file to be read from and write to at randomlocations.

    RandomAccessFile

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    32/268

    RandomAccessFile

    Creates a RandomAccessFile stream with the specified File object and

    mode.

    Creates a RandomAccessFile stream with the specified file name

    string and mode.

    Closes the stream and releases the resource associated with the stream.

    Returns the offset, in bytes, from the beginning of the file to where the

    next read or write occurs.

    Returns the length of this file.

    Reads a byte of data from this file and returns1 an the end of stream.

    Reads up to b.length bytes of data from this file into an array of bytes.

    Reads up to len bytes of data from this file into an array of bytes.

    Sets the offset (in bytes specified in pos) from the beginning of the

    stream to where the next read or write occurs.

    Sets a new length of this file.

    Skips over n bytes of input discarding the skipped bytes.

    Writes b.length bytes from the specified byte array to this file, startingat the current file pointer.

    Writes len bytes from the specified byte array starting at offset off to

    this file.

    DataInput DataInput

    java.io.RandomAccessFile

    +RandomAccessFile(file: File, mode:

    String)

    +RandomAccessFile(name: String,

    mode: String)

    +close(): void

    +getFilePointer(): long

    +length(): long

    +read(): int

    +read(b: byte[]): int

    +read(b: byte[], off: int, len: int) : int

    +seek(long pos): void

    +setLength(newLength: long): void

    +skipBytes(int n): int

    +write(b: byte[]): void

    +write(byte b[], int off, int len)+write(b: byte[], off: int, len: int):

    void

    Fil P i

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    33/268

    File Pointer

    A random access file consists of a sequence of bytes.

    There is a special marker calledfile pointerthat ispositioned at one of these bytes. A read or writeoperation takes place at the location of the file pointer.When a file is opened, the file pointer sets at the

    beginning of the file. When you read or write data to thefile, the file pointer moves forward to the next data. Forexample, if you read an int value using readInt(), theJVM reads four bytes from the file pointer and now the

    file pointer is four bytes ahead of the previous location.

    bytefile byte byte byte byte byte byte byte byte byte byte byte

    file pointer

    bytefile byte byte byte byte byte byte byte byte byte byte byte

    file pointer

    (A) Before readInt()

    (B) Before readInt()

    i M h d

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    34/268

    RandomAccessFile Methods

    Many methods in RandomAccessFile are the same as those

    in DataInputStream and DataOutputStream. Forexample, readInt(), readLong(), writeDouble(),readLine(), writeInt(), and writeLong() can be usedin data input stream or data output stream as well as inRandomAccessFile

    streams.

    M h d

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    35/268

    RandomAccessFile Methods, cont.

    void seek(long pos) throws

    IOException;

    Sets the offset from the beginning of the

    RandomAccessFile stream to where the next read

    or write occurs.

    long getFilePointer()

    IOException;

    Returns the current offset, in bytes, from the

    beginning of the file to where the next read

    or write occurs.

    i M h d

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    36/268

    RandomAccessFile Methods, cont.

    long length()IOException

    Returns the length of the file.

    final void writeChar(int v)

    throws IOException

    Writes a character to the file as a two-byte Unicode, with

    the high byte written first.

    final void writeChars(String s)

    throws IOExceptionWrites a strin to the file as a se uence of

    R d A Fil C t t

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    37/268

    RandomAccessFile Constructor

    RandomAccessFile raf =

    new RandomAccessFile("test.dat", "rw");//allows read and write

    RandomAccessFile raf =

    new RandomAccessFile("test.dat", "r");//read only

    Case Studies: Address BookOptional

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    38/268

    Case Studies: Address Book

    Now let us use RandomAccessFile to create a useful project for

    storing and viewing and address book. The user interface of theprogram is shown in Figure 16.24. TheAddbutton stores a new

    address to the end of the file. The First,Next, Previous, and

    Lastbuttons retrieve the first, next, previous, and last addresses

    from the file, respectively.

    Fixed Length String I/O

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    39/268

    Fixed Length String I/O

    Random access files are often used to process files of

    records. For convenience, fixed-length records areused in random access files so that a record can belocated easily. A record consists of a fixed number offields. A field can be a string or a primitive data type.

    A string in a fixed-length record has a maximum size.If a string is smaller than the maximum size, the rest ofthe string is padded with blanks.

    Record 1 Record 2 Record n

    Field1 Field 2 Field k

    file

    e.g.,

    Student 1 Student 2 Student n

    name street city state zip

    FixedLengthStringIO

    http://localhost/var/www/apps/conversion/tmp/scratch_6/html/FixedLengthStringIO.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_6/html/FixedLengthStringIO.html
  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    40/268

    End of Presentation

    Binary Input & OutputChapter 18

    Class #15 Input and OutputHow is I/O Handled in Java?

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    41/268

    ITP 120 Java Programming I41

    Patrick Healy

    A File object encapsulates the properties of a file or a path, but does not contain the methods for

    reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate

    Java I/O classes.

    Formatter output = new Formatter(outfile.txt");

    output.format("%s", "Java 120"); // Write a string to outfile.txt

    output.close(); // Close the output file outfile.txt

    Scanner input = new Scanner(new File("temp.txt")); // Create object

    System.out.println(input.nextLine()); // Read a line

    Program

    Input objectcreated from an

    input class

    Output object

    created from an

    output class

    Input stream

    Output stream

    File

    File010111001

    110011011

    Class #15 Input and OutputText Files vs. Binary Files

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    42/268

    ITP 120 Java Programming I42

    Patrick Healy

    Data stored in a text file are represented in human-readable form. Data storedin a binary file are represented in binary form. Youcannot read binary files.

    Binary files are designed to be read by programs. For example, the Javasource programs are stored in text files and can be read by a text editor, butthe Java classes are stored in binary files and are read by the JVM. Theadvantage of binary files is that they are more efficient to process than textfiles.

    Although it is not technically precise and correct, you can imagine that a textfile consists of a sequence of characters and a binary file consists of asequence of bits. For example, the decimal integer 199 is stored as thesequence of three characters: '1', '9', '9' in a text file and the same integer is

    stored as a byte-type value C7 in a binary file ( Note: decimal 199 equals toHex C7.)

    Class #15 Input and OutputBinary File I/O

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    43/268

    ITP 120 Java Programming I43

    Patrick Healy

    y

    Text I/O requires encoding and decoding. The JVM converts a Unicode char to a file-

    specific encoding when writing a character and coverts a file-specific encoding to a Unicode

    char when reading a character. Binary I/O does not require conversions. When you write a

    byte to a file, the original byte is copied into the file. When you read a byte from a file, the

    exact byte in the file is returned.

    Text I/O program

    The Unicode of

    the characterEncoding/

    Decoding

    Binary I/O program

    A byte is read/written(b)

    (a)

    e.g.

    "199"

    The encoding of the character

    is stored in the file

    0x31

    e.g.

    199 00110111

    00110001 00111001 00111001

    0x39 0x39

    0xC7

    The same byte in the file

    Class #15 Input and OutputBinary I/O Classes Inheritance Hierarchy

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    44/268

    ITP 120 Java Programming I44

    Patrick Healy

    InputStream

    OutputStream

    Object

    ObjectOutputStream

    FilterOutputStream

    FileOutputStream

    BufferedInputStream

    DataInputStream

    BufferedOutputStream

    DataOutputStream

    PrintStream

    ObjectInputStream

    FilterInputStream

    FileInputStream

    Class #15 Input and OutputInputStream (a byte stream class)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    45/268

    ITP 120 Java Programming I45

    Patrick Healy

    java.io.InputStream

    +read(): int

    +read(b: byte[]): int

    +read(b: byte[], off: int,len: int): int

    +available(): int

    +close(): void

    +skip(n: long): long

    +markSupported(): boolean+mark(readlimit: int): void

    +reset(): void

    Reads the next byte of data from the input stream. The value byte is returned asan int value in the range 0 to 255. If no byte is available because the end of

    the stream has been reached, the value1 is returned.

    Reads up to b.length bytes into array b from the input stream and returns the

    actual number of bytes read. Returns -1 at the end of the stream.

    Reads bytes from the input stream and stores into b[off], b[off+1], ,

    b[off+len-1]. The actual number of bytes read is returned. Returns -1 at the

    end of the stream.

    Returns the number of bytes that can be read from the input stream.

    Closes this input stream and releases any system resources associated with the

    stream.

    Skips over and discards n bytes of data from this input stream. The actualnumber of bytes skipped is returned.

    Tests if this input stream supports the mark and reset methods.Marks the current position in this input stream.

    Repositions this stream to the position at the time the mark method was last

    called on this input stream.

    The value returned is a byte as an int type.

    Class #15 Input and OutputOutputStream ( a byte stream class)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    46/268

    ITP 120 Java Programming I46

    Patrick Healy

    The value is a byte as an int type.

    java.io.OutputStream

    +write(int b): void

    +write(b: byte[]): void+write(b: byte[], off: int,

    len: int): void

    +close(): void

    +flush(): void

    Writes the specified byte to this output stream. The parameter b is an int value.(byte)b is written to the output stream.

    Writes all the bytes in array b to the output stream.Writes b[off], b[off+1], , b[off+len-1] into the output stream.

    Closes this input stream and releases any system resources associated with thestream.

    Flushes this output stream and forces any buffered output bytes to be written out.

    Class #15 Input and OutputFileInputStream & FileOutputStream (byte streams)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    47/268

    ITP 120 Java Programming I47

    Patrick Healy

    p p ( y )

    FileInputStream/FileOutputStream associates a binaryinput/output stream with an external file. All the methods

    in FileInputStream/FileOuptputStream are inherited fromits superclasses.

    InputStream

    OutputStream

    Object

    ObjectOutputStream

    FilterOutputStream

    FileOutputStream

    BufferedInputStream

    DataInputStream

    BufferedOutputStream

    DataOutputStream

    PrintStream

    ObjectInputStream

    FilterInputStream

    FileInputStream

    Class #15 Input and Output

    FileInputStream (byte stream)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    48/268

    ITP 120 Java Programming I48

    Patrick Healy

    FileInputStream (byte stream)

    To construct a FileInputStream, use the following constructors:

    public FileInputStream(String filename)

    public FileInputStream(File file)

    A java.io.FileNotFoundException would occur if you attemptto create a FileInputStream with a nonexistent file.

    Class #15 Input and OutputFileOutputStream (byte stream)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    49/268

    ITP 120 Java Programming I49

    Patrick Healy

    To construct a FileOutputStream, use the following constructors:public FileOutputStream(String filename)

    public FileOutputStream(File file)public FileOutputStream(String filename, boolean append)

    public FileOutputStream(File file, boolean append) // append = true to add on to the file

    If the file does not exist, a new file would be created. If the file already exists,

    the first two constructors would delete the current contents in the file. Toretain the current content and append new data into the file, use the last twoconstructors by passing true to the append parameter.

    Demo Program: TestFileStream.java

    Class #15 Input and OutputFilterInputStream/FilterOutputStream

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    50/268

    ITP 120 Java Programming I50

    Patrick Healy

    p p

    Filter streams are streams that filter bytes for some purpose. The basic byte inputstream provides a read method that can only be used for reading bytes. If you want toread integers, doubles, or strings, you need a filter class to wrap the byte input stream.

    Using a filter class enables you to read integers, doubles,and strings instead of bytes andcharacters. FilterInputStream and FilterOutputStream are the base classes for filteringdata. When you need to process primitive numeric types, use DataInputStream andDataOutputStream to filter bytes.

    InputStream

    OutputStream

    Object

    ObjectOutputStream

    FilterOutputStream

    FileOutputStream

    BufferedInputStream

    DataInputStream

    BufferedOutputStream

    DataOutputStream

    PrintStream

    ObjectInputStream

    FilterInputStream

    FileInputStream

    Class #15 Input and Output

    DataInputStream & DataOutputStream (byte streams)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    51/268

    ITP 120 Java Programming I51

    Patrick Healy

    DataInputStream & DataOutputStream (byte streams)

    DataInputStream reads bytes from the stream andconverts them into appropriate primitive type valuesor strings.

    InputStream

    OutputStream

    Object

    ObjectOutputStream

    FilterOutputStream

    FileOutputStream

    BufferedInputStream

    DataInputStream

    BufferedOutputStream

    DataOutputStream

    PrintStream

    ObjectInputStream

    FilterInputStream

    FileInputStream

    DataOutputStream converts primitive type values or strings into bytes and

    outputs the bytes to the stream.

    Class #15 Input and Output

    DataInputStream ( byte stream)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    52/268

    ITP 120 Java Programming I52

    Patrick Healy

    p ( y )

    DataInputStream extends FilterInputStream and implements the

    DataInput interface.

    java.io.DataInput

    +readBoolean(): boolean

    +readByte(): byte

    +readChar(): char+readFloat(): float

    +readDouble(): float

    +readInt(): int

    +readLong(): long

    +readShort(): short

    +readLine(): String

    +readUTF(): String

    Reads a Boolean from the input stream.

    Reads a byte from the input stream.

    Reads a character from the input stream.Reads a float from the input stream.

    Reads a double from the input stream.

    Reads an int from the input stream.

    Reads a long from the input stream.

    Reads a short from the input stream.

    Reads a line of characters from input.

    Reads a string in UTF format.

    InputStream

    FilterInputStream

    DataInputStream

    +DataInputStream(

    in: InputStream)

    Class #15 Input and OutputDataOutputStream (byte stream)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    53/268

    ITP 120 Java Programming I53

    Patrick Healy

    DataOutputStream extends FilterOutputStream and implements the DataOutput interface.

    java.io.DataOutput

    +writeBoolean(b: Boolean): void

    +writeByte(v: int): void

    +writeBytes(s: String): void

    +writeChar(c: char): void

    +writeChars(s: String): void

    +writeFloat(v: float): void

    +writeDouble(v: float): void

    +writeInt(v: int): void

    +writeLong(v: long): void

    +writeShort(v: short): void

    +writeUTF(s: String): void

    Writes a Boolean to the output stream.

    Writes to the output stream the eight low-order bits

    of the argument v.

    Writes the lower byte of the characters in a string to

    the output stream.

    Writes a character (composed of two bytes) to the

    output stream.

    Writes every character in the string s, to the output

    stream, in order, two bytes per character.

    Writes a float value to the output stream.

    Writes a double value to the output stream.

    Writes an int value to the output stream.

    Writes a long value to the output stream.

    Writes a short value to the output stream.

    Writes two bytes of length information to the output

    stream, followed by the UTF representation of

    every character in the string s.

    OutputStream

    FilterOutputStream

    DataOutputStream

    +DataOutputStream(

    out: OutputStream)

    Class #15 Input and OutputCharacters and Strings in Binary I/O

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    54/268

    ITP 120 Java Programming I54

    Patrick Healy

    A Unicode char is 2 bytes. The writeChar(char ch) method writes the Unicode of character chto the output. The writeChars(String str) method writes the Unicode for each character in thestring str to the output file.

    What is UTF-8 ? Why use UTF-8 ? [ UTF means Unicode Text File ]

    UTF-8 is a coding scheme that allows systems to operate with both ASCII and Unicode efficiently. Most

    operating systems use ASCII. Java uses Unicode. The ASCII character set is a subset of the Unicodecharacter set. Since most applications need only the ASCII character set, it is a waste to represent an8-bit ASCII character as a 16-bit Unicode character. The UTF-8 is an alternative scheme that stores acharacter using 1, 2, or 3 bytes. ASCII values (less than 0x7F) (127 decimal) are coded in one byte.Unicode values less than 0x7FF are coded in two bytes. Other Unicode values are coded in three bytes.

    Class #15 Input and Output

    Using DataInputStream/DataOutputStream

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    55/268

    ITP 120 Java Programming I55

    Patrick Healy

    Using DataInputStream/DataOutputStream

    Data streams are used as wrappers on existing input and output streams tofilter data in the original stream. They are created using the following

    constructors:public DataInputStream(InputStream instream)

    public DataOutputStream(OutputStream outstream)

    The statements below create data streams. The first statement creates aninput stream for file in.dat; the second statement creates an output stream forfile out.dat.

    DataInputStream infile =

    new DataInputStream(new FileInputStream("in.dat"));

    DataOutputStream outfile =

    new DataOutputStream(new FileOutputStream("out.dat"));

    Demo Program: TestDataStream.java

    Class #15 Input and Output

    Order and Format

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    56/268

    ITP 120 Java Programming I56

    Patrick Healy

    Checking for the End of File (EOF)

    TIP: If the program tried to read data at the end of a stream, an EOFExceptionwould occur. How do you check the end of a file? Use input.available() tocheck for EOF. if input.available() == 0 then the program is at the end of a file.

    (EOF)

    Order and Format

    CAUTION: You have to read the data in the same order and same format in

    which they are stored. For example, if names are written in UTF-8 usingwriteUTF (String str), you MUST read the names using the readUTF method.

    Class #15 Input and Output

    BufferedInputStream/

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    57/268

    ITP 120 Java Programming I57

    Patrick Healy

    BufferedInputStream/BufferedOutputStream Use buffers to speed up I/O processes

    InputStream

    OutputStream

    Object

    ObjectOutputStream

    FilterOutputStream

    FileOutputStream

    BufferedInputStream

    DataInputStream

    BufferedOutputStream

    DataOutputStream

    PrintStream

    ObjectInputStream

    FilterInputStream

    FileInputStream

    BufferedInputStream/BufferedOutputStream does not contain new methods. All the methodsBufferedInputStream/BufferedOutputStream are inherited from the InputStream/OutputStream classes.

    Class #15 Input and Output

    Constructing BufferedInputStream/BufferedOutputStream

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    58/268

    ITP 120 Java Programming I58

    Patrick Healy

    Constructing BufferedInputStream/BufferedOutputStream

    // Create a BufferedInputStream

    public BufferedInputStream(InputStream in)public BufferedInputStream(InputStream in, int bufferSize)

    // Create a BufferedOutputStream

    public BufferedOutputStream(OutputStream out)

    public BufferedOutputStream(OutputStream out, int bufferSize)

    Class #15 Input and OutputCopyFile.java

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    59/268

    ITP 120 Java Programming I59

    Patrick Healy

    CopyFile.java is a program that copies files. The user needs to provide a sourcefile and a target file as command-line arguments using the following command:

    java CopyFile source target

    Also: java CompFile source target

    The program copies a source file to a target file and displays the number of bytesin the file. If the source does not exist, tell the user the file is not found. If the target

    file already exists, tell the user the file already exists.

    Class #15 Input and OutputObject I/O (optional)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    60/268

    ITP 120 Java Programming I60

    Patrick Healy

    DataInputStream/DataOutputStream enables you to perform I/O for primitive type values andstrings. ObjectInputStream/ObjectOutputStream enables you to perform I/O for objects in

    addition for primitive type values and strings.

    InputStream

    OutputStream

    Object

    ObjectOutputStream

    FilterOutputStream

    FileOutputStream

    BufferedInputStream

    DataInputStream

    BufferedOutputStream

    DataOutputStream

    PrintStream

    ObjectInputStream

    FilterInputStream

    FileInputStream

    Class #15 Input and Output

    ObjectInputStream (optional)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    61/268

    ITP 120 Java Programming I61

    Patrick Healy

    ObjectInputStream (optional)

    ObjectInputStream extends InputStream and implements ObjectInput and

    ObjectStreamConstants.

    java.io.ObjectInput

    +readObject(): Object Reads an object.

    java.io.InputStream

    java.io.ObjectInputStream

    +ObjectInputStream(in: InputStream)

    java.io.DataInput

    ObjectStreamConstants

    Class #15 Input and Output

    ObjectOutputStream (optional)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    62/268

    ITP 120 Java Programming I62

    Patrick Healy

    ObjectOutputStream (optional)

    ObjectOutputStream extends OutputStream and implements ObjectOutput and

    ObjectStreamConstants.

    java.io.ObjectOutput

    +writeObject(o: Object): void Writes an object.

    ava.io.OutputStream

    java.io.ObjectOutputStream

    +ObjectOutputStream(out: OutputStream)

    java.io.DataOutput

    ObjectStreamConstants

    Class #15 Input and OutputUsing Object Streams (optional)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    63/268

    ITP 120 Java Programming I63

    Patrick Healy

    You may wrap an ObjectInputStream/ObjectOutputStream on anyInputStream/OutputStream using the following constructors:

    // Create an ObjectInputStream

    public ObjectInputStream(InputStream in)

    // Create an ObjectOutputStream

    public ObjectOutputStream(OutputStream out)

    Demo: TestObjectOutputStream.java

    TestObjectInputStream.java

    Class #15 Input and OutputTheSerializable Interface

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    64/268

    ITP 120 Java Programming I64

    Patrick Healy

    Not all objects can be written to an output stream. Objects that CANbe written to an object

    stream is said to be serializable. A serializable object is an instance of the java.io.Serializable

    interface. So the class of a serializable object must implement the Serializable interface.

    The Serializable interface is a marker interface. It has no methods, so you don't need to add

    additional code in your class that implements Serializable.

    Implementing this interface enables the Java serialization mechanism to automate the process

    of storing the objects and arrays.

    Class #15 Input and Output

    Thetransient Keyword

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    65/268

    ITP 120 Java Programming I65

    Patrick Healy

    If an object is an instance of Serializable, but it contains non-serializable instance data fields,

    can the object be serialized? The answer is NO !

    To enable the object to be serialized, you can use the transient keyword to mark these data

    fields to tell the JVM to ignore these fields when writing the object to an object stream.

    Class #15 Input and OutputThetransient Keyword, cont.

    Consider the following class:

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    66/268

    ITP 120 Java Programming I66

    Patrick Healy

    g

    public class ITP120 implements java.io.Serializable {

    private int v1;private static double v2;

    private transient A v3 = new A();

    }

    class A { } // A is not serializable

    When an object of the ITP120 class is serialized, only variable v1 isserialized. Variable v2 is not serialized because it is a static variable, andvariable v3 is not serialized because it is marked transient. If v3 were notmarked transient, a java.io.NotSerializableException would occur.

    Class #15 Input and Output

    Serializing Arrays (optional)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    67/268

    ITP 120 Java Programming I67

    Patrick Healy

    An array is serializable if all its elements are serializable. So an entire array can be saved

    using writeObject into a file and later restored using readObject.

    Listing 18.6 stores an array of five int values, an array of three strings, and an array of two

    JButton objects, and reads them back to display on the console.

    Demo Program: TestObjectStreamForArray.java

    Class #15 Input and Output

    Random Access Files

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    68/268

    ITP 120 Java Programming I68

    Patrick Healy

    All of the streams you have used so far are known as read-onlyorwrite-onlystreams. The

    external files of these streams are sequentialfiles that cannot be updated without creating

    a new file.

    It is often necessary to modify files or to insert new records into files. Java provides the

    RandomAccessFile class to allow a file to be read from and write to at random locations.

    Class #15 Input and OutputRandomAccessFile

    DataInput DataInput

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    69/268

    ITP 120 Java Programming I69

    Patrick Healy

    Creates a RandomAccessFile stream with the specified File object andmode.

    Creates a RandomAccessFile stream with the specified file name

    string and mode.

    Closes the stream and releases the resource associated with the stream.

    Returns the offset, in bytes, from the beginning of the file to where the

    next read or write occurs.

    Returns the length of this file.

    Reads a byte of data from this file and returns1 an the end of stream.

    Reads up to b.length bytes of data from this file into an array of bytes.

    Reads up to len bytes of data from this file into an array of bytes.

    Sets the offset (in bytes specified in pos) from the beginning of the

    stream to where the next read or write occurs.

    Sets a new length of this file.

    Skips over n bytes of input discarding the skipped bytes.

    Writes b.length bytes from the specified byte array to this file, startingat the current file pointer.

    Writes len bytes from the specified byte array starting at offset off to

    this file.

    java.io.RandomAccessFile

    +RandomAccessFile(file: File, mode:String)

    +RandomAccessFile(name: String,

    mode: String)

    +close(): void

    +getFilePointer(): long

    +length(): long

    +read(): int

    +read(b: byte[]): int

    +read(b: byte[], off: int, len: int) : int

    +seek(long pos): void

    +setLength(newLength: long): void

    +skipBytes(int n): int

    +write(b: byte[]): void

    +write(byte b[], int off, int len)+write(b: byte[], off: int, len: int):

    void

    Class #15 Input and OutputFile Pointers

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    70/268

    ITP 120 Java Programming I70

    Patrick Healy

    A random access file consists of a sequence of bytes. There is a specialmarker called file pointerthat is positioned at one of these bytes. A read or

    write operation takes place at the location of the file pointer. When a file isopened, the file pointer sets at the beginning of the file. When you read orwrite data to the file, the file pointer moves forward to the next data. Forexample, if you read an int value using readInt(), the JVM reads four bytesfrom the file pointer and now the file pointer is four bytes ahead of the

    previous location.

    Class #15 Input and OutputFile Pointers

    (moving the pointer 4 bytes ahead)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    71/268

    ITP 120 Java Programming I71

    Patrick Healy

    bytefile byte byte byte byte byte byte byte byte byte byte byte

    file pointer

    bytefile byte byte byte byte byte byte byte byte byte byte byte

    file pointer

    (A) Before readInt()

    (B) Before readInt()

    Class #15 Input and Output

    RandomAccessFile Methods

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    72/268

    ITP 120 Java Programming I72

    Patrick Healy

    Many methods in RandomAccessFile are the same as those in

    DataInputStreamand DataOutputStream.

    For example, readInt(), readLong(),writeDouble(), readLine(),writeInt(), andwriteLong()

    can be used in data input stream or data output stream as well as inRandomAccessFile streams.

    Class #15 Input and OutputRandomAccessFile Methods, cont.

    void seek(long pos) throws IOException;

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    73/268

    ITP 120 Java Programming I73

    Patrick Healy

    void seek(long pos) throws IOException;

    Sets the offset from the beginning of the RandomAccessFile stream to

    where the next reador write occurs.

    long getFilePointer() IOException;

    Returns the current offset, in bytes, from the

    beginning of the file to where the next reador write occurs.

    Class #15 Input and Output

    RandomAccessFile Methods, cont.

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    74/268

    ITP 120 Java Programming I74

    Patrick Healy

    long length()IOException

    Returns the length of the file.

    final void writeChar(int v) throwsIOException

    Writes a character to the file as a two-byte Unicode, with the high byte written

    first.

    final void writeChars(String s)throws IOException

    Writes a string to the file as a sequence of

    characters.

    Class #15 Input and Output

    RandomAccessFile Constructors

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    75/268

    ITP 120 Java Programming I75

    Patrick Healy

    RandomAccessFile raf =new RandomAccessFile("test.dat", "rw"); //allows read

    and write to the file

    RandomAccessFile raf =new RandomAccessFile("test.dat", "r"); //read only

    Demo program: TestRandomAccessFile.java

    (uses FixedLengthStringIO.java)

    Case Study: Address Book

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    76/268

    Now let us use RandomAccessFile to create a useful project for

    storing and viewing and address book. The user interface of the

    program is shown in Figure 16.24. TheAddbutton stores a new

    address to the end of the file. The First,Next, Previous, and

    Lastbuttons retrieve the first, next, previous, and last addresses

    from the file, respectively.

    Run: AddressBook.java which uses FixedLengthStringIO.java

    Fixed Length String I/O

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    77/268

    Random access files are often used to process files of

    records. For convenience, fixed-length records areused in random access files so that a record can belocated easily. A record consists of a fixed number offields. A field can be a string or a primitive data type.

    A string in a fixed-length record has a maximum size.If a string is smaller than the maximum size, the rest ofthe string is padded with blanks.

    Record 1 Record 2 Record n

    Field1 Field 2 Field k

    file

    e.g.,

    Student 1 Student 2 Student n

    name street city state zip

    FixedLengthStringIO

    Chapter 18 Demo Programs

    http://localhost/var/www/apps/conversion/tmp/scratch_6/html/FixedLengthStringIO.htmlhttp://localhost/var/www/apps/conversion/tmp/scratch_6/html/FixedLengthStringIO.html
  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    78/268

    78

    ReadBytes.java (skip) WriteData.java

    WriteDemo.java ReadData.java

    ShowFile.java

    CopyFile.java CopyFileUsingByteStream.java

    CompFile.java

    RWData.java

    RandomAccessDemo.java

    PrintWriterDemo.javaReadChars.java or BuffReader.java

    ReadLines.java (BufferedReader)

    Chapter 18 Demo Programs

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    79/268

    79

    TextFileScannerDemo.java

    Uses input file morestuff.txt

    HasNextLineDemo.java

    Uses input file original.txt

    and creates output file numbered.txt BufferReaderDemo.java

    Uses input file: buffer.txt

    Chapter 18 Demo Programs

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    80/268

    80

    TestDataStreams.java

    TestFileClass.java

    TestPrintWriters.java

    ViewFile.java (GUI text file viewer program)

    needs MyFrameWithExitHanding.java class file

    ParsingTextFile.java (needs grades.dat file)

    (creates gradesout.dat)

    TestRandomAccessFile.java

    AddressBook.java (creates file address.dat)

    needs FixedLengthStringIO.class file

    Chapter 18 Demo Programs

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    81/268

    81

    TestDataStream.java

    TestFileReader.java (needs temp.txt)

    TestFileStream.java

    TestFileWriter.java (needs testdata.txt)

    TestObjectStreamForArray.java ( creates array.dat)

    TestObjectOutputStream.java

    (creates object.dat)

    TestObjectInputStream.java (reads object.dat)

    Class #15 Input and OutputChapter 18 Input / Output

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    82/268

    ITP 120 Java Programming I82

    Patrick Healy

    Optional: More on Java File I/O

    Chapter 18 Java I ITP 120

    Class #15 Input and OutputChapter 18: More on Input and Output

    Stream Classes (byte & character streams)Predefined Streams (System in System out System err)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    83/268

    ITP 120 Java Programming I83

    Patrick Healy

    Predefined Streams (System.in, System.out, System.err)

    Processing External Files

    Data Streams

    Print Streams

    Buffered Streams

    Text Input and Output on the Console

    Random Access Files

    Class #15 Input and OutputChapter 18 Input /Output Objectives

    Understand input & output streams and learn how to create them.

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    84/268

    ITP 120 Java Programming I84

    Patrick Healy

    Discover the uses of byte and character streams.

    To know how to read from / write to external files using file streams. To become familiar with the File class.

    To use print streams to output data of primitive types in text format.

    To know how to read and write text data files.

    Use text input and output on the console.

    Use RandomAccessFile for reading & writing random access files.

    Class #15 Input and OutputOverview

    The java.io.*package provides a library of classes to read and writevarious types of data

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    85/268

    ITP 120 Java Programming I85

    Patrick Healy

    various types of data.

    In Java, all data I/O is handled in the form of streams

    Data streams can be byte streams or character streams

    The java.io package has classes that process byte streams of all types

    NOTE: In Java, a character is 2 BYTES !

    NOTE: Unicode character is 2 bytes !

    The Reader and Writer classes process character streams.

    Streams can be layered, so that one type of streams can be convertedto another type of streams by chaining. Chaining a character streamreader to a byte stream reader to read bytes on one end and produce

    characters at the other end .

    Class #15 Input and OutputOverview Streams

    In Java, all Input/Output is handled by streams

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    86/268

    ITP 120 Java Programming I86

    Patrick Healy

    A stream is an abstraction of the continuous one-way flow of data

    Java streams can be applied to any source of data, so it is easy to getinput from the keyboard and send output to a monitor, and the same

    applies to file input & output.

    All streams EXCEPT random-access file streams flow only in one

    direction.

    See the diagram on the next slide

    Class #15 Input and OutputOverview --- Streams

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    87/268

    ITP 120 Java Programming I87

    Patrick Healy

    A stream is an abstraction of a continuous one-way flow of data.

    Program

    Output Stream

    File

    Input Stream

    Class #15 Input and OutputOverview and Background

    The original version of Java defined only the byte stream, but character

    streams were quickly added

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    88/268

    ITP 120 Java Programming I88

    Patrick Healy

    streams were quickly added.

    Byte streams can be used when reading or writing binary data. Character streams are designed for handling character I/O.

    Character streams use UNICODE. In Java, a character is 2 bytes

    Unicode is for the internationalization of Java in different languages.

    The Java I/O system is quite LARGE because of the TWO separateclass hierarchies of bytes and streams.

    How is I/O Handled in Java?A File object encapsulates the properties of a file or a path, but does not contain

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    89/268

    the methods for reading/writing data from/to a file. In order to perform I/O, you

    need to create objects using appropriate Java I/O classes.

    Formatter output = new Formatter("temp.txt");output.format("%s", "Java ITP 120");

    output.close();

    Scanner input = new Scanner(new File("temp.txt"));

    System.out.println(input.nextLine());

    Program

    Input object

    created from aninput class

    Output object

    created from an

    output class

    Input stream

    Output stream

    File

    File010111001

    110011011

    Class #15 Input and OutputText Files vs. Binary Files

    Data stored in a text file are represented in human-readable form. Data

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    90/268

    ITP 120 Java Programming I90

    Patrick Healy

    pstored in a binary file are represented in binary form. You cannot read

    binary files. Binary files are designed to be read by programs. For example,the Java source programs are stored in text files and can be read by a texteditor, but the Java classes are stored in binary files and are read by theJVM.

    The advantage of binary files is that they are more efficient to process than

    text files.

    Although it is not technically precise and correct, you can imagine that atext file consists of a sequence of characters and a binary file consists of asequence of bits. For example, the decimal integer 199 is stored as the

    sequence of three characters: '1', '9', '9' in a text file and the same integer isstored as a byte-type value C7 in a binary file, because decimal 199 equalsto hex C7 ( 12 x 16 + 7 = 192 + 7 = 199 decimal )

    Binary I/O

    Text I/O requires encoding and decoding. The JVM converts a Unicode

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    91/268

    character to file-specific encoding when writing a character, and coverts

    a file-specific encoding to a Unicode character when reading a character.Binary I/O does not require conversions. When you write a byte to a file,

    the original byte is copied into the file. When you read a byte from a file,

    the exact byte in the file is returned.

    Text I/O program

    The Unicode of

    the character

    Encoding/

    Decoding

    Binary I/O program

    A byte is read/written(b)

    (a)

    e.g.

    "199"

    The encoding of the character

    is stored in the file

    0x31

    e.g.

    199 00110111

    00110001 00111001 00111001

    0x39 0x39

    0xC7

    The same byte in the file

    Class #15 Input and Output2 Types of Stream Classes: Bytes & Characters

    The stream classes can be categorized into two types: byte streams and

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    92/268

    ITP 120 Java Programming I92

    Patrick Healy

    The stream classes can be categorized into two types: byte streams and

    character streams.

    The InputStream/OutputStreamclass is the

    root of all byte stream classes

    The Reader/Writer class is the root of all character stream

    classes.

    The subclasses ofInputStream/OutputStreamare analogous to thesubclasses ofReader/Writer.

    Class #15 Input and OutputByte Stream Classes (note: stream )

    DataInputStream

    FileInputStream

    ByteArrayInputStreamInputData

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    93/268

    ITP 120 Java Programming I93

    Patrick Healy

    InputStream

    OutputStream

    RandomAccessFile

    Object

    PipeOutputStream

    SequenceInputStream

    StringBufferInputStream

    ByteArrayOutputStream

    ObjectOutputStream

    FilterOutputStream

    FileOutputStream

    PipedInputStream

    PushBackInputStream

    BufferedInputStream

    LineNumberInputStream

    BufferedOutputStream

    DataOutputStream

    PrintStream

    ObjectInputStream

    FilterInputStream

    FileInputStream

    OutputData

    ObjectOutput

    ObjectInput

    Class #15 Input and OutputCharacter Stream Classes (Character = 2 bytes)

    FileReaderInputStreamReader

    CharArrayReader

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    94/268

    ITP 120 Java Programming I94

    Patrick Healy

    Reader

    Writer

    StreamTokenizer

    Object

    PrintWriter

    BufferedWriter

    CharArrayWriter

    PipedWriter

    FilterWriter

    PipedReader

    LineNumberReader

    PushBackReader

    FileWriter

    StringWriter

    StringReader

    BufferedReader

    FilterReader

    OutputStreamWriter

    Class #15 Input and Output

    Predefined Streams in Java

    All Java programs automatically import the java.lang package.

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    95/268

    ITP 120 Java Programming I95

    Patrick Healy

    The java.lang package defines a class called System whichencapsulates several aspects of the runtime environment.

    The System class contains 3 predefined stream variables called:

    in, out, and err (System.in, System.out, System.err)

    These variables are declared as public and static with the System

    class. This means they can be used by any other part of your program

    and without a reference to a specific object in the System class.

    Class #15 Input and OutputPredefined Streams in Java: System class

    System.in refers to the standard input stream which is the

    keyboard by default. (Keyboard )

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    96/268

    ITP 120 Java Programming I96

    Patrick Healy

    y y ( y )

    System.out refers to the standard output stream which is the

    console by default. (Monitor)

    System.err refers to the standard error stream which is also theconsole by default. (Monitor)

    These streams may be redirected to any compatible I/O device.

    Class #15 Input and Output

    Predefined Streams in Java: System class

    System.in is an object of type InputStream. (byte stream)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    97/268

    ITP 120 Java Programming I97

    Patrick Healy

    System.out is an object of type PrintStream. (byte stream)

    System.err is an object of type PrintStream. (byte stream)

    They are all byte streams and are a part of the original Javaspecification.

    They are NOT character streams ! (Unicode character = 2 bytes)

    Class #15 Input and Output

    Reading Keyboard Input

    // Read an array of bytes from the keyboard.

    import java.io.*;

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    98/268

    ITP 120 Java Programming I98

    Patrick Healy

    public class ReadBytes {

    public static void main(String[ ] args)throws IOException {

    byte data[ ] = new byte[10]; // Byte array data holds 10 bytes

    System.out.println("Enter some characters:");

    System.in.read(data); // Use the read method to read some bytes

    System.out.print("You entered: ");

    for(int i=0; i < data.length; i++)

    System.out.print((char) data[i]); // Cast data to a character

    } // End main method

    } // End class ReadBytes

    Class #15 Input and Output

    Reading Keyboard Input

    Here is a sample run from the previous program:

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    99/268

    ITP 120 Java Programming I99

    Patrick Healy

    Enter some characters: (prompt from program)READ BYTES (User entered READ BYTES)

    You entered: READ BYTES (output from program)

    Class #15 Input and Output

    Writing Output to the Monitor

    // Demonstrate System.out.write(). Java program WriteDemo.java

    public class WriteDemo

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    100/268

    ITP 120 Java Programming I100

    Patrick Healy

    {

    public static void main(String[ ] args)

    {

    int b; // Program prints an X on the monitor

    b = 'X'; // The character is an int

    System.out.write(b); // A byte stream; write low-order 8 bits

    System.out.write('\n'); // Print a newline character \n

    } // End of main( ) // print() and println() are easier to use than write()

    } // End of class WriteDemo

    Class #15 Input and Output

    Stream classes (Bytes & Characters)

    The java.io package provides two categories of classes: Byte stream readers and writers

    Ch t t d d it

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    101/268

    ITP 120 Java Programming I101

    Patrick Healy

    Character stream readers and writers

    At the top of the hierarchy for stream classes are the abstract classesInputStream and Output Stream

    The subclasses branch out and specializes into the different types ofstreams that they handle.

    InputData, OutputData, and ObjectInput interfaces are implemented bythe classes that handle data, such as, int, double, char, etc., andobjects. Only ObjectInput specifies methods for reading objects.

    DataInputStream - which is a subclass of FilterInputStream, which inturn is a subclass of InputStream implements the InputData interface

    and can read primitive data, and objects from byte streams.

    Class #15 Input and Output

    Stream Classes

    FileInputStream can read raw streams of data from files.

    DataOutputStream can write primitive data; this class implements the

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    102/268

    ITP 120 Java Programming I102

    Patrick Healy

    p p ; p

    OutputData interface

    RandomAccessFile implements both InputData and OutputData

    interfaces, therefore, it can read and write data to streams.

    ObjectOutputStream implements the ObjectOutputinterface and can

    write object data to streams.

    Class #15 Input and Output

    InputStream Class (for reading bytes)

    The following methods are defined in InputStream

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    103/268

    ITP 120 Java Programming I103

    Patrick Healy

    and are often useful:

    public abstract int read() throws IOException

    Reads the next byte and returns its value in therange of 0 to 255. At the end of the stream, itreturns a - 1.

    public int read(byte b[]) throws IOExceptionReads bytes into array b,, returns b.length if thenumber of available bytes is >= b.length. Returnsthe number of bytes read if the number of available

    bytes is < than b.length, and returns 1 at the endof the stream.

    Class #15 Input and Output

    InputStream Class (for reading bytes)

    The following methods are defined in InputStream and

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    104/268

    ITP 120 Java Programming I104

    Patrick Healy

    are often useful:

    public void close() throws IOException

    This method closes the input stream.

    public void available() throws IOException

    Returns the number of bytes that can be read fromthe input stream without blocking.

    Class #15 Input and Output

    InputStream Class (for reading bytes)

    The following method is defined in InputStream and isf f l

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    105/268

    ITP 120 Java Programming I105

    Patrick Healy

    often useful:

    public long skip(long n) throws IOException

    Skip over and discard n bytes of data from theinput stream. The actual number of bytes skipped

    is returned.

    Class #15 Input and Output

    Reading & Writing Files Using Byte Streams

    To create a byte stream linked to a file, use FileInputStream or

    FileOutputStream

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    106/268

    ITP 120 Java Programming I106

    Patrick Healy

    To open a file, create an object of one of these classes, specifying the

    name of the file as an argument to the constructor.

    Once the file is open, you can read from the file or write to the file.

    To read form a file, you may use the read( ) method.

    int read( ) throws IOException

    When you are done with a file, you should close it by calling close()

    void close( ) throws IOException

    Closing a file releases the system resources allocated to the file,

    allowing them to be used by another file.

    Class #15 Input and Output

    Reading & Writing Files Using Byte Streams

    /* Display a text file.

    To use this program, specify the name

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    107/268

    ITP 120 Java Programming I107

    Patrick Healy

    of the file that you want to see.For example, to see a file called TEST.TXT,

    use the following command line.

    Command line usage: java ShowFile TEST.TXT */

    // Program ShowFile.java follows on the next slide ->

    Class #15 Input and Output

    Reading & Writing Files Using Byte Streams

    public class ShowFile {

    public static void main(String[ ] args)

    throws IOException {

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    108/268

    ITP 120 Java Programming I108

    Patrick Healy

    p {

    int i;

    FileInputStream fin; // Declare file pointer

    try {

    fin = new FileInputStream(args[0]); } // Open the input file

    catch(FileNotFoundException exc) {

    System.out.println(Error: + exc.getMessage( ));

    System.out.println("File Not Found");

    return; }

    } catch(ArrayIndexOutOfBoundsException exc) {

    System.out.println(Error: + exc.getMessage( ));

    System.out.println("Usage is: java ShowFile File.txt ");

    return; }

    Class #15 Input and Output

    Reading & Writing Files Using Byte Streams

    // Read bytes until EOF is encountered

    do {

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    109/268

    ITP 120 Java Programming I109

    Patrick Healy

    i = fin.read( ); // Read an integerif(i != -1) System.out.print((char) i); // Cast the int as a char

    } while( i != -1); // When i = -1, EOF is encountered

    fin.close( ); // Close the input file

    } // End of main method

    } // End of class ShowFile

    Class #15 Input and Output

    Writing to a File Using Byte Streams

    /* Java program to Copy a text file.

    To use this program, specify the name

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    110/268

    ITP 120 Java Programming I110

    Patrick Healy

    of the source file and the destination file.For example, to copy a file called File1.txt

    to a file called File2.txt , use the following

    on the command line:

    Usage: java CopyFile File1.txt File2.txt */

    Class #15 Input and Output

    Writing to a File Using Byte Streams

    // CopyFile.java Demo byte stream file operations

    import java.io.*;

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    111/268

    ITP 120 Java Programming I111

    Patrick Healy

    public class CopyFile {public static void main(String[ ] args) throws IOException

    {

    int i;

    FileInputStream fin; // Declare 2 byte stream files (pointers)

    FileOutputStream fout; // Output file pointer

    Class #15 Input and Output

    Writing to a File Using Byte Streams

    try { // outer try block

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    112/268

    ITP 120 Java Programming I112

    Patrick Healy

    // try to open input file

    try { // inner try

    fin = new FileInputStream(args[0]);

    } catch(FileNotFoundException exc) {System.out.println(Error:

    + exc.getMessage( ) );

    System.out.println("Input File Not Found");

    return; }

    Class #15 Input and Output

    Writing to a File Using Byte Streams

    // open output file

    try {

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    113/268

    ITP 120 Java Programming I113

    Patrick Healy

    fout = new FileOutputStream(args[1]);} catch(FileNotFoundException exc) {

    System.out.println(Error: + exc.getMessage());

    System.out.println("Error Opening Output File");

    return;

    }

    } // End of outer try block

    Class #15 Input and Output

    Writing to a File Using Byte Streams

    catch(ArrayIndexOutOfBoundsException exc) {

    System.out.println(Error: + exc.getMessage( ) );

    System.out.println("Usage: CopyFile File1 File2");

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    114/268

    ITP 120 Java Programming I114

    Patrick Healy

    return; }try { // Try to copy file1 to file2

    do {

    i = fin.read( ); // Read a byte

    if(i != -1) fout.write(i); // Write the byte to the output file

    } while(i != -1); // Loop while not at EOF (-1)} // End of try block

    catch(IOException exc)

    { System.out.println("File Error"); }

    fin.close( ); // Close the input file

    fout.close( ); // Close the output file

    } // End of main( ) method

    } // End of class CopyFile

    Class #15 Input and Output

    Reading & Writing Binary Data

    So far, we have been reading and writing bytes containingASCIIbytes.

    You may want to create a file that contains other types of data such as

    integers doubles or shorts that is: int double short etc

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    115/268

    ITP 120 Java Programming I115

    Patrick Healy

    integers, doubles, or shorts , that is: int, double, short, etc.

    In Java, to read and write binary values of the simple Java data types,

    you should use:

    DataInputStream and DataOutputStream (for binary data)

    DataOutputStream implements the OutputData interface.

    The OutputDatainterface defines methods that write all of Javas

    simple data types to a file.

    Class #15 Input and Output

    Reading & Writing Binary Data

    Note: Binary data is NOT in human-readable text format, obviously.

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    116/268

    ITP 120 Java Programming I116

    Patrick Healy

    The constructor for DataOutputStream is:

    DataOutputStream(OutputStream outputStream)

    outputStream is the stream to which the binary data is written.

    Class #15 Input and Output

    Reading & Writing Binary Data

    The constructor for DataInputStream is:

    DataInputStream(InputStream inputStream)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    117/268

    ITP 120 Java Programming I117

    Patrick Healy

    inputStream is the stream that is linked to the instance of

    DataInputStream being created.

    DataInputStream implements the DataInputinterface which providesthe methods for reading all of Javas simple data types.

    DataInputStream uses an InputStream instance as its foundation,

    overlaying it with methods that read the various Java data types.

    Class #15 Input and Output

    Reading & Writing Binary Data Examples

    To create an input stream for the file in.dat ( bytes)

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    118/268

    ITP 120 Java Programming I118

    Patrick Healy

    DataInputStream infile =new DataInputStream(new FileInputStream(in.dat));

    To create an output stream for the file out.dat:

    DataOutputStream outfile =

    new DataOutputStream(new FileOutputStream(out.dat));

    Class #15 Input and Output

    Reading & Writing Binary Data

    Common Input Methods Defined by DataInputStream (a byte stream)

    Input Method Purpose

    boolean readBoolean ( ) Reads a boolean

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    119/268

    ITP 120 Java Programming I119

    Patrick Healy

    boolean readBoolean ( ) Reads a boolean

    byte readByte ( ) Reads a byte

    char readChar ( ) Reads a char

    double readDouble( ) Reads a double

    float readFloat ( ) Reads a floatint readInt ( ) Reads an int

    long readLong ( ) Reads a long

    short readShort ( ) Reads a short

    Class #15 Input and Output

    Reading & Writing Binary Data

    Common Output Methods Defined by DataOutputStream ( byte stream)

    Output Method Purpose

    void writeBoolean (boolean val) writes the boolean specified by val

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    120/268

    ITP 120 Java Programming I120

    Patrick Healy

    void writeBoolean (boolean val) writes the boolean specified by val

    void writeByte (int val) writes the low-order byte val

    void writeChar(int val) writes the value val as a char

    void writeDouble(double val) writes the double val

    void writeFloat(float val) writes the float valvoid writeInt(int val) writes the int val

    void writeLong(long val) writes the long val

    void writeShort(int val) writes val as a short

    Class #15 Input and Output

    Reading & Writing Binary Data

    Here is a Java program that demonstrates DataOutputStream and

    DataInputStream. It writes and then reads back various types of data

    to and from a file.

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    121/268

    ITP 120 Java Programming I121

    Patrick Healy

    // Write and then read back binary data.

    import java.io.*;

    public class RWData {

    public static void main(String[ ] args) throws IOException

    {

    DataOutputStream dataOut; // Declare output, input file pointers

    DataInputStream dataIn;

    Class #15 Input and Output

    Reading & Writing Binary Data

    int i = 120;

    double d = 1049.56;

    boolean b = true;

  • 7/29/2019 itp120chapt192009binaryinputoutput-091011054706-phpapp01.ppt

    122/268

    ITP 120 Java Programming I122

    Patrick Healy

    ;

    try {

    dataOut = new

    DataOutputStream(new FileOutputStream(testdata")); }

    catch(IOException exc) {

    System.out.println(Error: + exc.getMessage( ));

    System.out.println("Cannot open file.");

    return; }

    Class #15 Input and Output

    Reading & Writing Binary Data

    try { // W