COMPE 438 JAVA PROGRAMMING - PowerPoint PPT Presentation


PPT – COMPE 438 JAVA PROGRAMMING PowerPoint presentation | free to view - id: a8108-N2I0M


The Adobe Flash plugin is needed to view this content

Get the plugin now

View by Category
About This Presentation



Text files: the bits represent printable characters ... they are not 'printable' files, 'printable' means 'easily readable by humans when printed' ... – PowerPoint PPT presentation

Number of Views:37
Avg rating:3.0/5.0
Slides: 43
Provided by: CEM4


Write a Comment
User Comments (0)
Transcript and Presenter's Notes


  • F. Cemile Serçe

Object-Oriented Application Frameworks
  • Application Frameworks
  • The Graphical User Interfaces Framework
  • The Collections Framework
  • The Input/Output Framework

I/O Overview
  • Data is input from and output to programs
  • Input From
  • Keyboard or a file
  • Output to
  • Display (screen) or a file
  • Text files Vs Binary files
  • Text files
  • represent printable characters Human readable
  • Binary files
  • represent other types encoded information, such
    as executable files, images or sounds

I/O Overview
  • Advantages of File I/O
  • Permanent copy
  • The data is lost when a local variable goes out
    of scope or when the program terminates
  • use files for long-term retention of large
    amounts of data, even after the programs that
    created the data terminated
  • file processing is one of the most important
    capabilities a language must have to support
    commercial applications, which typically store
    and process massive amounts of persistent data
  • Output from one program can be input to another
  • Input can be automated (rather than entered

The Input/Output Framework
  • flexible and easily configurable
  • support two types of input/output
  • Stream I/O (sequential access)
  • Stream-based
  • Reading or writing sequentially
  • may be opened for reading or writing, but not
  • Random Access I/O (random access)
  • Reading or writing at any position of a file
  • may be opened for both reading and writing

  • Stream an object that either delivers data to
    its destination (screen, file, etc.) or that
    takes data from a source (keyboard, file, etc.)
  • it acts as a buffer between the data source and
  • Input stream a stream that provides input to a
  • is an input stream
  • Output stream a stream that accepts output from
    a program
  • System.out is an output stream
  • A stream connects a program to an I/O object
  • System.out connects a program to the screen
  • connects a program to the keyboard

Stream I/O
  • Java communicates with the outside world using
  • A stream is a sequence of data
  • Java view each file as a sequential streams of

A program uses an input stream to read data from
a source, one item at a time
A program uses an output stream to write data to
a destination, one item at time
If you want to read and write the same
destination, you use 2 streams
Binary vs. Text Files
  • All data and programs are ultimately just zeros
    and ones
  • each digit can have one of two values, hence
  • bit is one binary digit
  • byte is a group of eight bits
  • Text files the bits represent printable
  • one byte per character for ASCII, the most common
  • for example, Java source files are text files
  • Binary files the bits represent other types of
    encoded information, such as executable
    instructions or numeric data
  • these files are easily read by the computer but
    not humans
  • they are not "printable" files, "printable" means
    "easily readable by humans when printed"

JavaBinary vs. Text Files
  • Text files are more readable by humans
  • Binary files are more efficient
  • computers read and write binary files more easily
    than text
  • Java binary files are portable
  • they can be used by Java on different machines
  • Reading and writing binary files is normally done
    by a program
  • text files are used only to communicate with

JavaBinary vs. Text Files
  • Number 127
  • Text file
  • Three bytes 1, 2, 7
  • ASCII (decimal) 49, 50, 55
  • ASCII (octal) 61, 62, 67
  • ASCII (binary) 00110001, 00110010, 00110111
  • Binary file
  • One byte (byte) 01111110
  • Two bytes (short) 00000000 01111110
  • Four bytes (int) 00000000 00000000 00000000

STORE the vaLue 5
  • byte streams
  • Storing data in its binary format
  • Binary files
  • character streams
  • Storing data as a sequence of characters
  • Text files

Byte Streams
public class CopyBytes public static void
main(String args) throws IOException
FileInputStream in null FileOutputStream
out null try in new
FileInputStream(input.txt") out new
FileOutputStream("output.txt") int c
while ((c ! -1)
out.write(c) finally if
(in ! null) in.close() if (out !
null) out.close()
Characters Streams
public class CopyCharacters public static
void main(String args) throws IOException
FileReader in null FileWriter out
null try in new FileReader
(input.txt") out new FileWriter
("characteroutput.txt") int c while ((c ! -1) out.write(c)
finally if (in ! null)
in.close() if (out ! null)
Buffered Streams
  • unbuffered I/O
  • each read or write request is handled directly by
    the underlying OS
  • less efficient, since each such request often
    triggers disk access, network activity, or some
    other operation that is relatively expensive

  • Not buffered each byte is read/written from/to
    disk as soon as possible
  • little delay for each byte
  • A disk operation per byte---higher overhead
  • Buffered reading/writing in chunks
  • Some delay for some bytes
  • Assume 16-byte buffers
  • Reading access the first 4 bytes, need to wait
    for all 16 bytes are read from disk to memory
  • Writing save the first 4 bytes, need to wait for
    all 16 bytes before writing from memory to disk
  • A disk operation per a buffer of bytes---lower

Buffered Streams
Buffer A small memory location that you use to
hold data temporarily
  • buffered I/O
  • Buffered input streams read data from a memory
    area known as a buffer the native input API is
    called only when the buffer is empty.
  • buffered output streams write data to a buffer,
    and the native output API is called only when the
    buffer is full.

in new BufferedReader(new FileReader(input.txt"
)) out new BufferedWriter(new
Buffered Streams
  • four buffered stream classes used to wrap
    unbuffered streams
  • BufferedInputStream and BufferedOutputStream
    create buffered byte streams,
  • BufferedReader and BufferedWriter create buffered
    character streams.

Line-Oriented I/O
  • Character I/O usually occurs in bigger units than
    single characters
  • One common unit is the line a string of
    characters with a line terminator at the end.
  • A line terminator can be a carriage-return/line-fe
    ed sequence ("\r\n"), a single carriage-return
    ("\r"), or a single line-feed ("\n")
  • Supporting all possible line terminators allows
    programs to read text files created on any of the
    widely used operating systems

Line-Oriented I/O
public class CopyCharacters public static
void main(String args) throws IOException
FileReader in null FileWriter out
null try in new
BufferedReader(new FileReader(input.txt"))
out new PrintWriter(new
FileWriter("output.txt")) String l
while ((l in.readLine()) ! null)
finally if (in ! null) in.close()
if (out ! null) out.close()

Text File Output
  • To open a text file for output connect a text
    file to a stream for writing
  • PrintWriter outputStream new PrintWriter(new
  • Similar to the long way
  • FileOutputStream s new FileOutputStream("out.txt
  • PrintWriter outputStream new PrintWriter(s)
  • Goal create a PrintWriter object
  • which uses FileOutputStream to open a text file
  • FileOutputStream connects PrintWriter to a text

Closing a File
  • An output file should be closed when you are done
    writing to it (and an input file should be closed
    when you are done reading from it).
  • For example, to close the file opened in the
    previous example
  • outputStream.close()
  • If a program ends normally it will close any
    files that are open

Text File Input
  • To open a text file for input connect a text
    file to a stream for reading
  • Goal a BufferedReader object,
  • which uses FileReader to open a text file
  • FileReader connects BufferedReader to the text
  • For example
  • BufferedReader smileyInStream
  • new BufferedReader(new FileReader(smiley.txt"))
  • Similarly, the long way
  • FileReader s new FileReader(smiley.txt")
  • BufferedReader smileyInStream new

Exception Handling with File I/O
  • IOException is a predefined class
  • File I/O might throw an IOException
  • catch the exception in a catch block that at
    least prints an error message and ends the
  • FileNotFoundException is derived from IOException
  • therefor any catch block that catches
    IOExceptions also catches FileNotFoundExceptions
  • put the more specific one first (the derived one)
    so it catches specifically file-not-found
  • then you will know that an I/O error is something
    other than file-not-found

Writing Formatted File Data
  • Use the DataInputStream and DataOutputStream
    classes to accomplish formatted input and output
  • DataOutputStream objects enable you to write
    binary data to an OutputStream
  • When you use a DataOutputStream connected to
    FileOutput Stream, this is known as chaining the
    stream objects

Data Streams
  • Data streams support binary I/O of primitive data
    type values (boolean, char, byte, short, int,
    long, float, and double) as well as String values
  • All data streams implement either the DataInput
    interface or the DataOutput interface
  • the most widely-used implementations of these
    interfaces, DataInputStream and DataOutputStream

Writing Formatted File Data
  • The DataOutput interface includes methods such
  • writeBoolean()
  • writeChar()
  • writeDouble()
  • writeFloat()
  • writeInt()

Reading Formatted File Data
  • DataInputStream objects enable you to read binary
    data from an InputStream
  • DataInput interface is implemented by

Reading Formatted File Data
  • The DataInput interface includes methods such as
  • readByte()
  • readChar()
  • readDouble()
  • readFloat()
  • readInt()
  • readUTF()

Using the File Class
  • File class does not provide any opening,
    processing, or closing capabilities for files
  • use the File class to obtain information about a
    file, such as whether it exists or is open, its
    size, and its last modification date
  • must include the statement
  • import
  • create a File object using a constructor that
    includes a filename
  • File someData new File(data.txt)

Using the File Class
Random Access Files
  • Streams provide a simple model for reading and
    writing data. Streams work with a large variety
    of data sources and destinations, including disk
  • However, streams don't support all the operations
    that are common with disk files
  • non-stream file I/O
  • File, examines and manipulates files and
  • Random access files , support nonsequential
    (random) access to disk file data.

Random Access Files
  • Sequential access files access records in
    sequential order from beginning to end
  • Random access files are files in which records
    can be accessed in any order
  • Also called direct access files
  • More efficient than sequential access files
  • examples of a good use of random access files
  • zip files
  • real-time applications

Random Access Files
  • An efficient way to extract a particular file
    from within a zip file is with a random access
  • open the file
  • find and read the directory locating the entry
    for the desired file
  • seek to the position of the desired file
  • read it
  • With a sequential access file, on average you'd
    have to read half the zip file before finding the
    file that you wanted. With a random access file,
    you only read the directory and the file that you

Create Random Access Files
  • The RandomAccessFile class contains the same
    read(), write() and close() methods as
    InputStream and OutputStream
  • Also contains seek() that lets you select a
    beginning position within the file before reading
    or writing data
  • Use Java's RandomAccessFile class to create your
    own random access files

Create Random Access Files (Examples)
  • The following code creates a RandomAccessFile to
    read the file named input.txt
  • new RandomAccessFile(input.txt", "r")
  • The following one opens the same file for both
    reading and writing
  • new RandomAccessFile(output.txt", "rw")
  • After the file has been opened, you can use the
    common read or write methods defined in the
    DataInput and DataOutput interfaces to perform
    I/O on the file.

Random Access Files File Pointer
  • RandomAccessFile supports the notion of a file
  • The file pointer indicates the current location
    in the file.
  • RandomAccessFile contains three methods for
    explicitly manipulating the file pointer.
  • int skipBytes(int) Moves the file pointer
    forward the specified number of bytes
  • void seek(long) Positions the file pointer just
    before the specified byte
  • long getFilePointer() Returns the current byte
    location of the file pointer

EXAMPLES(Reading Text from Standard Input)
try BufferedReader in new
BufferedReader(new InputStreamReader(System.i
n)) String str while ((str ! null)
str in.readLine()
System.out.println(str) catch
(IOException e)

EXAMPLES(Reading Text from File)
try BufferedReader in new
FileReader(content.txt")) String str while
((str in.readLine()) ! null)
System.out.println(str) in.close()
catch (IOException e)

EXAMPLES(Writing to File)
try BufferedWriter out new
out.write("aString") out.close() catch
(IOException e)

If the file does not already exist, it is
automatically created.
EXAMPLES(Append to a File)
try BufferedWriter out new
FileWriter(filename, true))
out.write("aString") out.close() catch
(IOException e)

EXAMPLES(Using a Random Access File)
try File f new File("filename")
RandomAccessFile raf new RandomAccessFile(f,
"rw") // Read a character char ch
raf.readChar() // Seek to end of file // Append to the
end raf.writeChars("aString")
raf.close() catch (IOException e)