File Handling
File Handling
– Output Stream.
– Input Stream.
Program
Output Stream
Key board
Monitor
Why Streams?
• Program becomes independent of the devices that
are used.
• Flushing buffers.
Streams
• Binary Streams: stores bytes of data
– 4 bytes for int type etc.
AudioInputStream SequenceInputStream
FileInputStream ByteArrayInputStream
PipedInputStream
ObjectInputStream
FilterInputStream
Basic output Stream operations
• Write() mirrors the InputStream class
OutputStream
FileOutputStream ByteArrayOutputStream
PipedOutputStream
ObjectOutputStream
FilterOutputStream
Stream Readers & Writers
• Readers and Writers are the objects that can
read or write byte streams as character
streams
InputStreamReader OutputStreamWriter
PipedReader PipedWriter
BufferedReader BufferedWriter
FilterReader FilterWriter
CharArrayReader CharArrayWriter
StringReader StringWriter
PrintWriter
Standard streams
• A standard input stream:
– Key board usually
– Encapsulated by ‘in’ member of the ‘System’ class
(type InputStream)
• A standard output stream:
– Output on the command line
– ‘out’ member of the ‘System’ class (type PrintStream)
• A standard error output stream:
– Error messages on to the command line
– ‘err’ member of the ‘System’ class (type PrintStream)
Tokenizing a stream
• A StreamTokenizer class defines objects
that can read an input stream and parse it
into tokens
• Kinds of tokens a streamTokenizer can
recognize:
– Numbers
– Strings
– Words
– Comments
– White spaces
Getting data from the keyboard
StreamTokenizer st = new
StreamTokenizer( new
BufferedReader(new
InputStreamReader(System.in)));
Accessing files and Directories
File handling
• Create and use the file objects to examine
files and directories
• Create new files and directories
• Create temporary files
• Writing on to the files
Working with file objects
• File object encapsulates a pathname or reference to a physical file or
directory
• Caution: File object does not check whether the given path is valid or
not.
• Note: for a File, specify the file name towards the end of the pathname
Creating files
• File objects are immutable