Professional Documents
Culture Documents
Stream-Based I/O
Objective
Data
Data Program
Input Stream
Output Stream
Input & Output Streams
Input Stream
This can be any source of serial data. It’s typically a disk file, the keyboard, or a
remote computer.
Output Stream
The output stream can be associated with any output device.
We can use this stream to transfer byte sequences to the device associated..
Binary & Character Streams
Types of Streams : 2
Binary or Byte Streams
Character Streams
• While writing data to a Binary Stream, the data is written as a series of bytes,
exactly as it appears in the memory. No data transformation takes place.
• With character streams, our program reads and writes Unicode characters, but the
stream will contain characters in the equivalent character encoding used by the
local computer.
InputStream & OutputStream
java.lang.Object
java.io.Flushable
java.io.InputStream
java.io.OutputStream
java.io.closeable
Closeable & Flushable
• Added by jdk 5.
• Offers a uniform way of specifying that a stream can be closed or flushed.
java.io.Closeable
public abstract void close( ) throws java.io.IOException
• close( ) closes the stream and release any resources that the stream object is
holding.
java.io.Flushable
public abstract void flush( ) throws java.io.IOException
Direct Subclasses : 7
InputStream
AudioInputStream ByteArrayInputStream
For reading audio data For reading from a byte array
FileInputStream SequenceInputStream
For reading from a file For reading from a sequence of streams
ObjectInputStream PipedInputStream
For reading objects from a stream For reading from a piped stream
FilterInputStream
For filtering input from an existing stream
FilterInputStream
No. of Subclasses : 9
• BufferedInputStream
Buffers input from another stream in memory to make the read operations
more efficient.
• DataInputStream
Reads data of primitive types from a binary stream.
• CheckedInputStream
Reads an input stream and maintains a checksum for the data that is read to
verify it integrity.
• CipherInputStream
Reads data from an encrypted input stream.
FilterInputStream contd.
• DigestInputStream
Reads data from an input stream and updates an associated message digest.
A message digest is a mechanism for combining an arbitrary amount of data
from a stream into a fixed-length value that can be used to verify the
integrity of the data.
• InflaterInputStream
Reads data from a stream that has been compressed, such as a ZIP file.
• LineNumberInputStream
Reads data from a stream and keeps track of the current line number. The
line number starts at 0 and is incremented each time a newline character is
read.
FilterInputStream contd.
• ProgressMonitorInputStream
Reads data from an input stream and uses a progressmonitor to monitor
reading the stream. If reading the stream takes a significant amount
of time, a progress dialog will be displayed offering the option to cancel
the operation. This is used in window- based applications for operations
that are expected to be time-consuming.
• PushbackInputStream
Adds the capability to return the last byte that was read back to the input
stream so you can read it again.
OutputStream
OutputStream
ObjectOutputStream ByteArrayOutputStream
For writing objects to a stream For writing to a byte array
FileOutputStream FilterOutputStream
For writing to a file For filtering output from an existing stream
PipedOutputStream
For writing to a piped stream
Stream Readers
Reader
InputStreamReader PipedReader
For reading a character stream For reading from a PipedWriter
BufferedReader CharArrayReader
For buffering other readers For reading from a char array
FilterReader StringReader
For reading filtered streams For reading from a String
Stream Writers
Writer
OutputStreamWriter PipedWriter
For writing a character stream For writing a PipedReader
BufferedWriter CharArrayWriter
For buffering other writers For writing to a char array
PrintWriter StringWriter
For writing formatted data For writing to a String
FilterWriter
For writing filtered streams
Standard Streams
• Operating system typically defines three standard streams that are accessible
through members of the System class.
Constants : 4
TT_EOF : indicates end of stream has been read
TT_EOL : indicates end of line has been read
TT_NUMBER : indicates a no. has been read
TT_WORD : indicates a word token has been read.
Instance Variables : 3
ttype : indicates the token type that has just been read by nextToken().
nval : holds the no.
sval : holds the word.
Using StreamTokenizer
while( st.nextToken()!=st.TT_EOF )
{
if( st.ttype==st.TT_NUMBER)
n++;
else if( st.ttype == st.TT_WORD)
w++;
}
System.out.println("Numbers in the file : "+n);
System.out.println("Words in the file : "+w);
Using StreamTokenizer contd.
• resetSyntax()
Resets the state of the tokenizer object so no characters have any special
significance. This has the effect that all characters are regarded as
ordinary and are read from the stream as single characters. The value of
each character will be stored in the ttype field.
• ordinaryChar(int ch)
Sets the character ch as an ordinary character. An ordinary character is
a character that has no special significance.
• The format parameter is a string that should contain at least one format
specification for each of the argument values that follow the format argument.
General Form :
%[argument_index$][flags][width][.precision]conversion
Formatted output to Command Line contd.
Conversion : This is a single character specifying how the argument is to be presented.
• Flags : a set of flag characters that modify the output format. The flag characters
that are valid depend on the conversion that is specified. Commonly used flags are
:
‘-’ and ‘^’ apply to anything and specify that the output should be left
justified and uppercase, respectively.
‘+’ forces a sign to be output for numerical values.
‘0’ forces numerical values to be zero-padded.
• Width
• Precision
Formatted output to Command Line contd.
Output
x = 33.750000 y = 0x1.b8p4
a = 255 b = 5 c = 17
Output
The string is:
The quick brown fox.
The quick brown fox.
Formatting Data into a String
Note :-
• Printf() method produces the string that is output by using an object of type
java.util.Formatter, and it is the Formatter object that is producing the output
string from the format string and the argument values.
• A Formatter object is also used by a static method format() that is defined in the
String class.
Output:
x = 27.50 y = 33.750
Formatting Data into a StringBuffer
System.out.print(buf);
Points to remember :
A Formatter object can format data and transfer it to destinations other than
StringBuilder and StringBuffer objects.
Accessing File System using java.io
When to use
• Used to check the pathname that it encapsulates against the physical file system
and see whether it corresponds to a real file or directory.
• Can be used to create file stream objects.
Under MS Windows the prefix for a path on a local drive will be a string
defining the drive, such as “C:\\” or “C:/”.
Under Unix the prefix will be a forward slash, “/”.
A path that include a prefix is called Absolute Path & since it includes a prefix it’s
not platform-independent.
• \\servername\directory_path\filename
• //servername/directory_path/filename
File f = new
File(File.separator+File.separator+”127.0.0.1”+File.separator+”common”+”.txt”);
Situation :
We want to create file objects referring to every files of the user’s home
directory and user’s working directory. Again the path must be platform-
independent.
Testing & Checking File Objects
getName()
Returns the name of the file or the directory without path.
getPath()
Returns a String object containing the path for the File object—including
the file or directory name.
isAbsolute()
Returns true if the File object refers to an absolute pathname, and false
otherwise.
getParent()
Returns a String object containing the name of the parent directory of the
file or directory represented by the current File object.
Note : When a file object is created using relative path, getParent() return null.
getParentFile()
Returns the parent directory as a File object, or null if this File object
does not have a parent.
equals(File)
Returns true if both File objects refers to the same file.
Querying Files & Directories
exists()
Returns true if the file or directory referred to by the File object exists
and false otherwise.
isDirectory()
Returns true if the File object refers to an existing directory and
false otherwise.
isFile()
isHidden()
canRead()
canWrite()
Both methods can throw SecurityException if user hasn’t read or write
access.
getAbsolutePath()
getAbsoluteFile()
Returns a File object containing the absolute path for the directory or
file referenced by the current File object.
Getting File List
String[] list()
The method will throw an exception of type SecurityException if
access to the directory is not authorized.
String[] list( FilenameFilter )
File[] listRoots()
returns an array of File objects referring to root directories in the current file
system.
long lastModified()
return value represents the time that the directory or file was last modified.
FileFilter & FilenameFilter
Interface java.io.FileFilter
boolean accept( File )
Interface java.io.FilenameFilter
boolean accept( File directory, String
filename )
• used to create temporary file. Prefix is the file name & must be at least 3
characters long. Suffix is the extension. If suffix is null .tmp will be used.
• If prefix or suffix are too long for file names on the current system, they will be
truncated, but neither will be truncated to less than three characters.
• If the directory argument is null, the system temporary directory will be used. If
the file cannot be created,
an IOException will be thrown. If prefix has less than three characters, an
IllegalArgumentException will be thrown.
Creating & Modifying Files & Folders
deleteOnExit()
• Causes the file or directory represented by the current File object to be deleted
when the program ends.
• This method does not return a value. The deletion will be attempted only if the
JVM terminates normally.
delete()
• This will delete the file or directory represented by the current File object and
return true if the delete was successful.
• It won’t delete directories that are not empty.
Tracing Space of a Storage Device
long getTotalSpace( )
long getFreeSpace( )
Constructors :
FileInputStream( File ) throws FileNotFoundException
FileInputStream( String ) throws FileNotFoundException
FileInputStream( FileDescriptor )
try{
FileInputStream fis = new FileInputStream( "Test.java" );
while( fis.available()>0 ){
System.out.print((char)fis.read());
}
}
catch(Exception e){
/* do something */
}
FileOutputStream
Constructors
FileOutputStream( String ) throws FileNotFoundException
FileOutputStream( String, boolean ) throws FileNotFoundException
FileOutputStream( File ) throws FileNotFoundException
FileOutputStream( File, boolean ) throws FileNotFoundException
FileOutputStream( FileDescriptor )
A FileDescriptor object represents an existing connection to a file, so since the
file must exist, this constructor does not throw an exception of type
FileNotFoundException.
FileDescriptor
• Can be used to create other stream objects when we want to have several
connected to the same file concurrently.
java.lang.Object
java.io.InputStream java.io.OutputStream
Java.io.FilterInputStream java.io.FilterOutputStream
java.io.DataInput java.io.DataOutput
Java.io.DataInputStream java.io.DataOutputStream
DataInputStream & DataOutputStream : Example
try{
FileOutputStream fos = new FileOutputStream("primitives.txt");
DataOutputStream dos = new DataOutputStream( fos );
dos.writeInt(50);
dos.writeBoolean(true);
dos.writeFloat(6.7f);
dos.close();
• Understanding Stream
• Scanning and Formatting
• I/O from command Line
• Standard Stream
Thank you