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

DataOutputStream in Java I/O Management

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)
35 views15 pages

DataOutputStream in Java I/O Management

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

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.
[Link] 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 [Link] .
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 [Link]
from the specified byte array to the outputStream.
[Link] 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.
[Link] CLASSES
The [Link] 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.
[Link] 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.
[Link]/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
}
[Link] OF FILES
Steps to create a File
[Link] name for the file.
[Link] type to be stored.
[Link] (reading, writing or updating).
[Link] 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:

[Link] salary
[Link] [Link]
inventory [Link]
 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 (“[Link]”);
....
}
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 (“[Link]”);
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
[Link] / 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 “[Link]” into afile called “[Link]”.

File inFile = new File (“[Link]”);


File outFile = new File (“[Link]”);
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 “[Link]”and “[Link]” are opened.
The statements
ch = [Link]();
Reads a character from the inFile through the input stream ins and assigns it to the variable ch.
Similarly, the statement,
[Link](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=[Link]()) != -1)
Causes the termination of the while loop when the end of the file is reached. The statements
[Link]();
[Link]();
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.

[Link]/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 “[Link]”.
Prompt> javac [Link]

[Link] 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 [Link].*;
public class FileTest09
{
public static void main(String[] args) throws IOException {
File f = new File("[Link]");
DataOutputStream dos = new DataOutputStream(new FileOutputStream(f));
[Link](2019);
[Link](true);
[Link]('S');
[Link](99.95);
[Link]();
DataInputStream dis = new DataInputStream(new FileInputStream(f));
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]();
}
}
Output:
C:\file>java File09
2019
true
S
81.95

Common questions

Powered by AI

Object serialization in Java is the process of reading and writing objects to and from streams, converting them into a byte stream that can be persisted to a file or transmitted over a network. It facilitates data management in file processing by enabling the storage and retrieval of complex objects in a way that maintains their state and structure. This allows Java programs to easily save object data to files and later reconstruct the objects back into memory, thereby supporting persistent data management .

DataInputStream and DataOutputStream classes are used in scenarios where reading and writing primitive data types, such as integers and doubles, is necessary. These classes serve as filters on existing input and output streams to process primitive data efficiently. They implement methods from parent classes via multiple inheritance, enabling seamless data handling, allowing for the reading and writing of primitive types without the need of converting them to byte format manually. This results in more straightforward and error-resistant code when managing varied data types .

Using secondary storage devices is preferred over variables and arrays in Java for handling large volumes of data because variables and arrays only provide temporary storage. Data is lost when a variable goes out of scope or when the program terminates. Secondary storage, such as floppy disks or hard disks, allows data to be persistently stored in files, overcoming the limitations of variables and arrays .

Buffered streams in Java, such as `BufferedInputStream` and `BufferedOutputStream`, provide significant performance enhancements over unbuffered streams by reducing the number of I/O operations and thus the frequency of direct system calls. By accumulating input data in a buffer, they allow multiple bytes to be read or written in one operation, minimizing overhead. This is particularly beneficial when working with large files or when network latency impacts operations, leading to more efficient and faster data processing .

Java streams offer a uniform, object-oriented interface that facilitates the flow of data between programs and input/output devices by abstracting the end-point details. Streams represent a sequence of data that can originate from the keyboard, mouse, memory, disk, network, or other programs, and may be directed towards the screen, printer, or another program. This abstraction allows programs to read from or write to diverse devices without needing to understand their specifics .

To create a file in Java, the following steps are involved: 1) Select a suitable filename unique on the disk and decide on its length and allowable characters; 2) Determine the data type to be stored, which informs the choice of file stream classes; 3) Define the purpose of the file, whether reading, writing, or updating; 4) Decide on the method of creating the file, choosing between direct or indirect approaches. Finally, initialize file stream objects, connect the file to a stream, and handle any I/O exceptions that may arise .

FileReader and FileWriter classes support reading and writing character data in Java by allowing 16-bit character streams to be associated with files. They handle I/O operations by reading characters from an input file or writing characters to an output file. File termination is handled by checking for the character `-1` in a read operation, indicating the end of a file. For example, the statement `while ((ch=ins.read()) != -1)` terminates the loop when the end of file is reached. This ensures proper management of file data until completion .

Exception handlers are crucial in managing Input/Output (I/O) operations in Java by catching and handling exceptions that may occur during file operations. They ensure the program can gracefully handle errors such as file not found or access denied. An exception handler should be implemented using a try-catch block, with the `try` section encompassing I/O statements and the `catch` section dealing with `IOException`. An example implementation is: `try { /* I/O statements */ } catch (IOException e) { /* Handle exception */ }`, which ensures program stability by addressing possible disruptions .

Java's input and output stream classes manage system resources by ensuring that streams are properly closed after use, which releases any associated system resources and enables garbage collection. Key methods involved include `close()`, which is explicitly used to close streams, and `flush()`, which writes buffered output bytes to their destination before closing a stream. Proper use of these methods prevents resource leaks and ensures efficient system performance .

Java's byte stream classes are designed for handling I/O operations on bytes and are suitable for binary data. In contrast, character stream classes manage I/O operations on characters and are ideal for textual data. The distinction is rooted in the type of data each handles - byte streams deal with 8-bit bytes, while character streams manage 16-bit Unicode characters, aligning with Java's use of Unicode .

You might also like