0% found this document useful (0 votes)
4 views15 pages

Unit 5 Java Full Notes

The document provides an overview of managing input and output files in Java, detailing concepts such as streams, stream classes, and methods for reading and writing data. It explains the importance of file processing for persistent data storage, introduces input and output streams, and outlines the creation and handling of files, including exceptions. Additionally, it covers reading/writing characters and bytes, as well as handling primitive data types using filter classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views15 pages

Unit 5 Java Full Notes

The document provides an overview of managing input and output files in Java, detailing concepts such as streams, stream classes, and methods for reading and writing data. It explains the importance of file processing for persistent data storage, introduces input and output streams, and outlines the creation and handling of files, including exceptions. Additionally, it covers reading/writing characters and bytes, as well as handling primitive data types using filter classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Unit - V

I/O Package: Managing Input / Output Files in Java: Introduction Concepts of Streams- Stream
Classes – Using streams -Input/Output Exceptions –Creation of files – Reading / Writing
Characters, Reading /Writing Bytes - Handling Primitive Data types.
1.MANAGING INPUT/ OUTPUT FILES IN JAVA
Introduction
1. The data is lost either when a variable goes out of scope or when the program is terminated.
That is, the storage is temporary.
2. It is difficult to handle large volumes of data using variables and arrays.
We can overcome these problems by storing data on secondary storage devices such as floppy
disks or hard disks. The data is stored in these devices using the concept of files, Data stored in
files is often called persistent data.
A file is a collection of related records placed in a particular area on a disk.
A record is composed of several fields and a field is a group of characters as illustrated.
Characters in Java are Unicode characters composed of two bytes, each byte containing eight
binary digits, 1 or 0.
Storing and managing data using files is known file processing which includes tasks such as
creating files, updating files and manipulation of data.
The process of reading and writing objects is called object serialization.
Methods of Java IO InputStreams
1. read() – The read() method is used to read the next byte of data from the Input Stream.
2. mark(int arg) – The mark(int arg) method is used to mark the current position of the
input .
3. reset() – The reset() method is invoked by mark() method. It changes the position of the
input stream back to the marked position.
4. close() – The close() method is used to close the input stream and releases system resources
associated with this stream to Garbage Collector.
read(byte [] arg) – The read(byte [] arg) method is used to read the number of bytes
of arg.length .
5. skip(long arg) – The skip(long arg) method is used to skip and discard arg bytes in the
input stream.


Methods of Java IO OutputStreams
 flush() – The flush() method is used for flushing the outputStream This method forces the
buffered output bytes to be written out.
 close() – The close() method is used to close the outputStream and to release the system
resources affiliated with the stream.
 write(int b) – The write(int b) method is used to write the specified byte to the
outputStream.
write(byte [] b) – The write(byte [] b) method is used to write bytes of length b.length
from the specified byte array to the outputStream.
2.CONCEPT OF STREAMS
In file processing, input refers to flow of data into a program.
Input to a program may come from the keyboard, the mouse, the memory, the disk, a
network, or another program.
output means the flow of data out of a program. Similarly, output from a program may go to
the screen, the screen, the printer, the memory, the disk, a network, or other program.

Java uses the concept of streams to represent the ordered sequence of data, a common
characteristic shared by all the input/output devices as stated above. A stream presents a
uniform, easy-to-use, object-oriented interface between the program and the input/output
devices. A stream in Java is a path along which data flows (like a river or a pipe along which
water flows).It has a source (data) and a destination (for that data)
The concept of sending data from one stream to another (like one pipe feeding into another) has
made streams in Java a powerful tool for file processing. Java streams are classified into two
basic types, namely, input stream and output stream.
An input stream extracts data from the source and sends it to the program.
An output stream takes data from the program and sends it to the destination .

The program connects and opens an input stream on the data source and then reads the data
serially.
the program connects and opens an output stream to the destination place of data and writes
data out serially. In both the cases, the program does not know the details of end points.
3.STREAM CLASSES
The java.io package contains a large number of stream classes that provide capabilities for
processing all types of data. These classes maybe categorized into two groups based on the data
type on which they operate.
1. Byte stream classes that provide support for handling I/O operations on bytes.
2. Character stream classes that provide support for managing I/O operations on characters.
These two groups may further be classified based on their purpose . Byte stream and
character stream classes contain specialized classes to deal with input and output operations
independently on various types of devices. The source (or destination) may be memory, a file
or a pipe.
4.USING STREAMS
Input and output stream classes used for handling both the 16-bit characters and 8-bit bytes.
Although all the classes are known as i/o classes, not all of them are used for reading and
writing operations only. Some perform operations such as buffering, filtering, data conversion,
counting and concatenation while carrying out i/o tasks.
5.INPUT/OUTPUT EXCEPTIONS
When creating files and performing i/o operations on them, the system may generate i/o
related exceptions.

Each i/o statement or group of i/o statements must have an exception handler around it as shown
below or the method must declare that it throws IOException.
try
{
…….
……. //I/O statements
…….
}
catch (IOException e)
{
……. // Message output statement
}
6.CREATION OF FILES
Steps to create a File
1.Suitable name for the file.
2.Data type to be stored.
3.Purpose (reading, writing or updating).
4.Method of creating the file.
 A filename is a unique string of characters that helps identify a file on the disk.
 The length of a filename and the characters allowed are dependent on the OS on which the
Java program is executed.
 A filename may contain two parts, a primary name and an optional period with extension.

 Example:

input.data salary
test.doc student.txt
inventory rand.dat
 Data type is important to decide the type of file stream classes to be used for handling the
data. 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 writing only, or
both the operations.
A file stream can be defined using the classes of Reader/InputStream for reading data and
Writer/OutputStream for writing data.

There are two ways of initializing the file stream objects.


Direct approach
FileInputStream fis;
try
{ //Assign the filename to the file stream object
fis = new FileInputStream (“test.dat”);
....
}
catch (IOException e)
....
....
The indirect approach uses a file object that has been initialized with the desired filename. This
is illustrated by the following code.
....
....
File inFile;
inFile = new File (“test.dat”);
FileInputStream fis;
try
{
//Give the value of the file object
//to the file stream object
fis = new FileInputStream (inFile);
....
}
catch (. . . . .)
.....
.....
The code above includes five tasks:
● Select a filename
● Declare a file object
● Give the selected name to the file object declared
● Declare a file stream
● Connect the file to the file stream object
7.READING / WRITING CHARACTERS
The two subclasses used forhandling charactersin files are FileReader (for reading characters)
andFileWriter (for writing characters). The below program uses these two file stream classes to
copy the contents of a file named “input.dat” into afile called “output.dat”.

File inFile = new File (“input.dat”);


File outFile = new File (“output.dat”);
The program then creates two file stream objects ins and outs and
initializes them with “null” as follows:
FileReader ins = null;
FileWriter outs = null;
These streams are then connected to the named files using the followingcode:
ins = new FileReader (inFile);
out = new FileWriter (outFile);
This connects inFile to the FileReader streams insand outFile to theFileWriter stream outs.
This essentially means that the files “input.dat”and “output.dat” are opened.
The statements
ch = ins.read();
Reads a character from the inFile through the input stream ins and assigns it to the variable ch.
Similarly, the statement,
outs.write(ch);
Writes the character stored in the variable ch to the outFilethrough theoutput stream outs. The
character-1 indicates the end of the file andtherefore the code
while ((ch=ins.read()) != -1)
Causes the termination of the while loop when the end of the file is reached. The statements
ins.close();
out.close();
Enclosed in the finally clause close the files created for reading and writing. When the program
catches an I/O exception, it prints a message and then exits from exception.

8.READING/WRITING BYTES
 FileReader and FileWriter classes to read and write 16-bit characters.
 most file systems use only 8-bit bytes. Two commonly used classes for handling bytes are
FileInputStream and FileOutputStream classes.
 use the in place of FileReader and FileWriter.

Note that the program requires the filename to be given as a commandline argument. This
program displays the following when we supply thefile name “city.txt”.
Prompt> javac ReadBytes.java

9.HANDLING PRIMITIVE DATA TYPES


 The basic input and output streams provide read/write methods that can only be used for
reading/writing bytes or characters.
 Read/write the primitive data types such as integers and doubles, we can use filter classes
as wrappers on existing input and output streams to filter data in the original stream. The two
filter classes used for creating“data streams” for handling primitive types are
DataInputStream and DataOutputStream.
 These classes use the concept of multiple inheritance and therefore implements all the
methods contained in both the parent class and the inheritance.
A data stream for input can be created as follows:
FileInputStream fis = new FileInputStream (infile);
DataInputStream dis = new DataInputStream (fis);
These statements first create the input file stream fis and then create the input data stream dis.
These statements basically wrap dis on fis and use it as a “filter”. Simultaneously, the following
statements create the output data stream dos and wrap it over the output file stream fos.

FileOutputStream fos = new FileOutputStream (outfile);


DataOutputStream dos = new DataOutputStream (fos);
Example:
import java.io.*;
public class FileTest09
{
public static void main(String[] args) throws IOException {
File f = new File("test.txt");
DataOutputStream dos = new DataOutputStream(new FileOutputStream(f));
dos.writeInt(2019);
dos.writeBoolean(true);
dos.writeChar('S');
dos.writeDouble(99.95);
dos.close();
DataInputStream dis = new DataInputStream(new FileInputStream(f));
System.out.println(dis.readInt());
System.out.println(dis.readBoolean());
System.out.println(dis.readChar());
System.out.println(dis.readDouble());
dis.close();
}
}
Output:
C:\file>java File09
2019
true
S
81.95

You might also like