Unit 5 IO
Unit 5 IO
IOSTREAM
INTRODUCTIO N
When we use variables and array for storing data inside the
programs. We face two Problems:
1) The data is lost either when a variable goes out of scope or when
the program is terminated. The storage is temporary.
2
A file is collection of related records placed area on the disk. A
record is composed of several fields. Field is a group of
characters.
3
CONCEPT OF STREAM
In file processing, input refers to the flow of data into a program
and output means the flow of data out of a program.
4
Java uses concept of stream to represent ordered sequence
of data, a common characteristics shared by all
input/output devices.
5
The concept of sending data from one stream to another has
made streams in java a powerful tool for file processing.
6
Stream
Input stream: it extracts (i.e. reads) data from the source (file) and sends it
to the program.
Output stream: it takes data from the program and sends (i.e. writes) it to
the destination (file).
7
Input stream
Reads
source Program
8
keyboard
standard input
stream
CPU
standardout
put stream MEM
monitor
terminal file
console input
stream
LOAD
READ HDD
What does information travel across?
Streams files
file output
stream
SAVE10
WRITE
STREAM CLASSES
The java.io package contains a large number of stream classes
that provide capabilities for processing all types of data.
11
These groups may further be classified based on their functions.
12
1) Byte stream classes
Byte stream classes have been designed to provide functional
features for creating and manipulating streams and files reading
and writing bytes.
⚫ readDouble()
⚫ readLine()
⚫ readChar()
⚫ readBoolean() 18
OUTPUT STREAM C L AS S ES
Data Output stream classes are derived from the base class Output
Stream as shown in figure.
19
Method Description
1 write() Writes a byte to the output
stream
20
The DataOutputStream, a counterpart of DataOutputStream,
implements the interface DataOutputStream .
⚫ writeDouble()
⚫ writeBytes()
⚫ writeChar()
⚫ writeBoolean()
21
C HARACTER ST R EAM
CLASSES
22
CHARACTER STREAM C L AS S E S
Character stream classes were not a part of the language when it
was released in 1995.
They were added later when the version 1.1 was announced.
23
READER STREAM C L AS S ES
Reader stream classes are designed to read character from the
files. Reader class is the base class for all other classes in this
group as shown in figure.
24
25
WRITER ST REAM C L A S S E S
Like output stream classes, the writer stream classes are
designed to perform all output operations on files.
26
USING STREAMS
29
Task Character Stream Byte Stream Class
Class
Performing input Reader InputStream
operations
Buffering input BufferedReader BufferdInputStream
Keeping track of LineNumberReader LineNumberInputStream
line numbers
Reading from an CharArrayReader ByteArrayInputStream
array
Translating byte InputStreamReader (none)
stream into a
character stream
Reading from files FileReader FileInputStream 30
Filtering the input FilterReader FilterInputStream
Task Character Byte Stream Class
Stream Class
Pushing back PushbackReader PushbackInputStream
characters/bytes
Reading from a pipe PipedReader PipedInputStream
Reading from a StringReader StringBufferInputStream
string
Reading primitive (none) DataInputStream
types
Performing output Writer OutputStream
operations
Buffering output BufferedWriter BufferedOutputStream
Writing to an array CharArrayWriter ByteArrayOutputStream31
Task Character Byte Stream Class
Stream Class
Filtering the output FilterWriter FilterOutputStream
Translating OutputStreamWri (none)
character stream ter
into a byte stream
Writing to a file FileWriter FileOutputStream
Printing values and PrintWriter PrintStream
objects
Writing to a pipe PipedWriter PipedOutputStream
Writing to a string String Writer (none)
Writing primitive (none) DataOutputStream
types 32
OTHER USEFUL CLASS
The java.io package supports many other classes for performing
certain specialized functions. They include among others:
RandomAccessFile :
The RandomAccessFile enables us to read and write bytes, text
and java data types to any location in a file. This class extends
object class and implements DataInput and DataOutput
interface
StreamTokenizer :
The class StreamTokenizer, a subclass of object can be used
for breaking up a stream of text from an input text file into
meaningful pieces called tokens. The behaviour of the
StreamTokenizer class is similar to that of StringTokenizer
class (of java.util package) that breaks string into its component
tokens.
32
O bject
interface interface
DataInput DataOutput
RandomAccessFile
33
USING THE FILE CLASS
The java.io package includes a class known as the File class
that provides support for creating files and directories. The
class includes several constructors for instantiating the File
objects.
File class provides methods for operations like:
⚫ Creating a file
⚫ Opening a file
⚫ Closing a file
⚫ Deleting a file
⚫ Getting the name of a file, Getting the size of a file
⚫ Checking the existence of a file
⚫ Renaming a file
⚫ Checking whether the file is writable
⚫ Checking whether the file is readable
34
I NPUT / OUT PUT E X C E P T I O N S
When creating files and performing I/O operations on them, the system
may generate I/O related exceptions. The basic I/O related exception
classes and their functions:
36
Data type is important to decide the type of file stream classes to
be used for handling the data. We should decide whether the data
to be handled is in the form of characters, bytes or primitive type.
The purpose of using a file must also be decided before using it. For
example, we should know whether the file is created for reading
only, or both the operations.
The common stream classes used for various i/o operations given in
table . The constructors of stream classes may be used to assign the
38
desired filenames to the Stream objects.
Source/destination Characters
Read Write
Memory CharArrayReader CharArrayWriter
File FileReader FileWriter
Pipe PipedReader PipedWriter
Source/destination Bytes
Read Write
ByteArrayOutputStrea
Memory ByteArrayInputStream
m
File FileInputStream FileoutputStream
Pipe PipedInputStream PipedoutputStream
39
There are two ways of initializing the file Stream objects.
39
DIRECT C R E AT I O N
FileInputStream fis;
try
{
//Assign the filename to the file stream object
fis = new FileInputStream (“test.txt”);
........
}
catch (IOException e)
...........
...........
40
I N D IR E C T C R E ATIO N
.............
File inFile;
InFile = new file (“test.txt”);
FileInputStream fis;
try
{
//give the value of the file object
//tothe file stream object
Fis=new FileInputStream (inFile);
..............
}
catch (......)
{
42
................
}
The code above includes five tasks:
Select a filename.
42
Reading/writing characters
As pointed out earlier, subclass of Reader and Writer implement
streams that can handle characters.
The concept of using file streams and file object for reading and
writing characters in program is illustrated in fig:
43
R EA D I N G / W R I T I N G BY T E S :
We have used FileReader and FileWriter classes to read
and write 16-bit characters.
44
FileOutputStream
• FileOutputStream class is used to write data, byte by byte, to a file.
• The creation of a FileOutputStream class is not dependent on the file
that already exists.
Constructors of FileOutputStream
• FileOutputStream(String name) throws FileNotFoundException
• This creates an output file stream to write to the file with the specified
name.
• FileOutputStream(File file) throws FileNotFoundException
• This creates a file output stream to write to the file represented by the
specified File object.
• FileOutputStream(FileDescriptor fd) throws FileNotFoundException
• This creates an output file stream to write to the specified file
descriptor, which represents an existing connection to an actual file in
the file system.
Constructors of FileOutputStream
• FileOutputStream(String name, Boolean append) throws
FileNotFoundException
• This creates an output file stream to write to the file with the specified
name.
• FileOutputStream(File file, Boolean append) throws
FileNotFoundException
• This creates a file output stream to write to the file represented by the
specified File object.
FileInputStream
• FileInputStream class is specially designed to work with byte-orented
input from files & is derived from InputStream.
• Constructors of FileInputStream are:
1. FileInputStream(File file)
2. FileInputStream(FileDescriptor fd)
3. FileInputStream(String name)
Constructors of FileInputStream
• public FileInputStream(String name)
• This creates a FileInputStream by opening a connection to an actual
file, the file named by the path name name in the file system.
• public FileInputStream(File file)
• This creates a FileInputStream by opening a connection to an actual
file, the file named by the File object file in the file system.
• public FileInputStream(FileDescriptor fd)
• This creates a FileInputStream by using the file descriptor fdObj,
which represents an existing connection to an actual file in the file
system.
//program to read data from file
import java.io.*;
class FISDemo {
public static void main(String args[]) throws IOException,
FileNotFoundException{
FileInputStream fis=new FileInputStream("hello.txt");
int data;
while((data= fis.read())!=-1){
System.out.print((char)data);
}
fis.close();
}
}
OUTPUT:
//program to write data in file
import java.io.*;
class FOSDemo {
public static void main(String args[]) throws IOException,
FileNotFoundException{
FileOutputStream fos=new FileOutputStream("hello.txt");
String s= "This is file output stream";
byte b[]=s.getBytes();
fos.write(b);
System.out.print("data is saved");
fos.close();
}
}
OUTPUT TEXT IN hello.txt flie: