0% found this document useful (0 votes)
2 views36 pages

MCA Java Programming Unit 6 Java Input Output

This document serves as a self-learning material for Java Input/Output, focusing on the concept of streams, including byte-oriented and character-oriented streams. It outlines the Java I/O classes, their hierarchies, and various methods for file handling, along with examples of using System.out, System.in, and System.err for output and input operations. The material also includes case studies, terminal questions, and assignments to reinforce learning objectives related to Java I/O functionality.

Uploaded by

surajpawar0229
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views36 pages

MCA Java Programming Unit 6 Java Input Output

This document serves as a self-learning material for Java Input/Output, focusing on the concept of streams, including byte-oriented and character-oriented streams. It outlines the Java I/O classes, their hierarchies, and various methods for file handling, along with examples of using System.out, System.in, and System.err for output and input operations. The material also includes case studies, terminal questions, and assignments to reinforce learning objectives related to Java I/O functionality.

Uploaded by

surajpawar0229
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Programming

Java Input/
Output
SELF LEARNING MATERIAL

SEM - I (103)

MCA
UNIT-6 JAVA INPUT/OUTPUT
TABLE OF CONTENTS

6.1 Introduction
6.2 Concept of streams
6.3 Console – [Link], [Link], [Link]
6.4 Byte-oriented streams
6.5 Character-oriented streams
6.6 Buffered streams
6.7 Serialization and deserialization
6.8 Summary
6.9 Case study
6.10 Terminal Questions
6.11 Answers
6.12 Assignment
6.13 References

Learning Objectives
• To understand the concept of streams in Java
• To learn about file handling in Java
• To study character and buffered stream used in Java
NOTES

6.1
Introduction
The protocols and classes offered by the Java programming language for
reading and writing data to and from various sources, such as files, network
connections, and memory buffers, are referred to as Java I/O (Input/Output).
Any programming language must provide input/output functions because
they allow programs to communicate with the outside world.

Streams, data sequences that may be read from or written to, are the
foundation of Java I/O. Byte and character streams are the two streams
offered by the Java I/O API. While character streams are used to read and
write text data, bytes streams are used to read and write binary data.

The Java I/O classes are organized into two hierarchies: the InputStream/
OutputStream hierarchy for byte streams, and the Reader/Writer hierarchy
for character streams. For various I/O operations, each hierarchy offers a
collection of abstract classes and concrete implementations.

The abstract superclass of all classes that represent input streams is


the InputStream class, while the abstract superclass of all classes that
represent output streams is the OutputStream class. Similar to how the
Reader class is the abstract superclass of all classes representing input
character streams, so too is the Writer class for all classes representing
output character streams.
01
NOTES Java has classes like FileInputStream and FileOutputStream for byte streams
and FileReader and FileWriter for character streams to conduct I/O operations
on files. These classes allow you to read from and write to files using various
methods such as reading single bytes or characters, reading and writing arrays
of bytes or characters, and more.

Apart from file-based I/O, Java also supports other types of I/O operations.
For example, network-based I/O can be achieved using classes such as
Socket and ServerSocket for TCP/IP communication, and classes like
URLConnection for working with URLs. Additionally, Java provides classes
like ByteArrayInputStream and ByteArrayOutputStream for I/O operations on
memory buffers.

Java I/O also includes support for buffering, which can significantly improve the
performance of I/O operations. BufferedInputStream and BufferedOutputStream
are used for buffering byte streams, while BufferedReader and BufferedWriter
are used for buffering character streams.

6.2
Concept of Streams
A stream is a collection of data components that can be functionally and
declaratively processed. It represents a pipeline of operations that can be
performed on the data, such as filtering, mapping, and reducing. Streams enable
us to perform complex data manipulation and transformation tasks with concise
and expressive code. They provide a higher-level abstraction over collections
and arrays, allowing for efficient and parallel processing of [Link] in Java
encourage a functional programming style, where operations are applied to
immutable data, making the code more predictable and thread-safe. With the
introduction of streams, Java has become more versatile and capable of handling
large-scale data processing tasks with greater ease and efficiency.

Types of streams
The Java model for I/O is completely based on streams. There are two types of
streams:
● Byte streams: These carry integers with values that range between 0 and
255. Diversified data can be represented in byte formats, like numerical data,
executable programs, and byte codes – the class file that runs a Java program.
● Character Streams: These are specialized types of byte streams that can
handle only textual data.

02
Byte Stream
Input Stream Class NOTES
Class
Output Stream Class
Java Stream
Classes
Reader Class
Character
Stream Class
Writer Class

Fig 1: Classification of Java Stream Classes

Byte Streams
Byte streams in Java are used for reading and writing binary data, such as raw
bytes, to and from different sources. They operate on data at the byte level, making
them suitable for handling non-textual data or binary files. The abstract classes
InputStream and OutputStream are the foundation for the byte stream classes.

InputStream and its Subclasses:


● All classes used to represent input byte streams belong to the abstract
superclass known as InputStream. It defines basic methods for reading bytes,
including read (), which reads a single byte of data, and read(byte[] buffer),
which reads a sequence of bytes into a buffer.
● FileInputStream is a subclass of InputStream that reads data from a file. It
provides methods like read (), read (byte [] buffer), and skip (long n) to read data
from a file.
● BufferedInputStream is a wrapper class that adds buffering capabilities to an
input byte stream. It improves performance by reducing the number of physical
read operations from the underlying stream.
● DataInputStream is a wrapper class that provides methods for reading Java
primitive data types from an input stream. It offers methods like readInt(),
readDouble(), and readUTF() to read data in a specific format.
● ObjectInputStream is a class used for deserializing objects from an input
stream. It allows you to reconstruct objects that were previously serialized
using ObjectOutputStream.

OutputStream and its Subclasses:


● OutputStream is the abstract superclass of all classes representing output
byte streams. It defines basic methods for writing bytes, including write (int
b), which writes a single byte of data, and write (byte [] buffer), which writes a
sequence of bytes from a buffer.
● A subclass of OutputStream called FileOutputStream writes data to a file. To
write data to a file, it has functions like write (int b), write (byte [] buffer), and
flush ().
● BufferedOutputStream is a wrapper class that adds buffering capabilities to
an output byte stream. It improves performance by reducing the number of
physical write operations to the underlying stream.

03
NOTES ● A wrapper class called DataOutputStream offers ways to write Java primitive
data types to an output stream. It offers methods like writeInt(), writeDouble(),
and writeUTF() to write data in a specific format.
● ObjectOutputStream is a class used for serializing objects to an output stream.
It allows you to convert objects into a stream of bytes that can be saved to a
file or transmitted over a network.

Character Streams

Java uses character streams to read and write text-based data, including strings
and characters, to and from various sources. They operate on data at the character
level, providing a higher-level abstraction for handling textual data. The character
stream classes are based on the abstract classes Reader and Writer.

Reader and its Subclasses:


● Reader is the abstract superclass of all classes representing input character
streams. It defines basic methods for reading characters, including read (),
which reads a single character, and read(char[] buffer), which reads a sequence
of characters into a buffer.
● FileReader is a subclass of Reader that reads data from a file as characters. It
provides methods like read (), read (char [] buffer), and skip (long n) to read data
from a file.
● BufferedReader is a wrapper class that adds buffering capabilities to an input
character stream. It improves performance by reducing the number of physical
read operations from the underlying stream and provides additional methods
like readLine() for reading lines of text.
● InputStreamReader is a class used for converting bytes to characters. It bridges
byte streams to character streams and can be used to specify a specific
character encoding when reading bytes.

Writer and its Subclasses:


● The abstract superclass of all classes that represent output character streams
is called Writer. Write (int c), which outputs a single character, and Write(Char[]
buffer), which outputs a string of characters from a buffer, are two of the
fundamental methods for writing characters that are defined.
● FileWriter is a subclass of Writer that writes data to a file as characters. It
provides methods like write (int c), write (char [] buffer), and flush() to write data
to a file.
● BufferedWriter is a wrapper class that adds buffering capabilities to an output
character stream. It improves performance by reducing the number of physical
write operations to the underlying stream and provides additional methods like
newLine() for writing new lines.
● OutputStreamWriter is a class used for converting characters to bytes. It
bridges character streams to byte streams and can be used to specify a specific
character encoding when writing characters.

04
CHECK YOUR PROGRESS
NOTES
1. InputStreamReader is used for converting bytes to characters in Java. [True/
False]
2. ____________ is a class used for converting characters to bytes in Java.
3. ____________ is the abstract superclass of all classes representing input byte
streams in Java.

Activity
Explore scenarios where byte streams are more suitable and where character
streams excel. Present your findings and discuss advantages and limitations of
each stream type.

6.3
Console- [Link], [Link],
[Link]

[Link]
System. out is the standard output stream used to produce a program’s result on
an output device like a computer [Link] various functions that are used to
output statements are:
● print(): This command is used to display text on the console. This text is passed
as the parameter in the form of a string. It prints the text on the console and
the cursor remains at the end of the text at the console. The next printing takes
place from this new cursor position.
● printf(): It is similar to printf in C. It is a simple method and it can take multiple
arguments.

Example:
public class PrintfExample {
public static void main (String [] args) {
String name = “John”;
int age = 25;
double salary = 5000.50;
[Link](“Name: %s%n”, name);
[Link](“Age: %d%n”, age);
[Link](“Salary: %.2f%n”, salary);
}
} 05
NOTES The program outputs:
Name: John
Age: 25
Salary: 5000.50

In this program, within the main() method, three variables are declared and initialized.
Formatted output is printed to the console using the [Link] function.
It is followed by parenthesis, within which we specify the format string and the
corresponding [Link] %s, %d, and %.2f are format specifiers used within
the printf() method. They specify the type and formatting of the corresponding
variables.
● %s is used for strings and is replaced by the value of the name variable.
● %d is used for integers and is replaced by the value of the age variable.
● %.2f is used for floating-point numbers and specifies that the value should
be displayed with two decimal places. It is replaced by the value of the salary
variable.
● The %n is a platform-independent newline character, which ensures that each
output appears on a new line.

[Link]
This is the standard input stream that is used to read characters from the keyboard
or any other common input device.

With [Link], you can read data from the user or an input source by using
the various methods provided by the InputStream class. These methods include
read(), which reads a single byte of data, and read(byte[] buffer), which
reads a sequence of bytes into a buffer. Consider the following example:

import [Link]. *;
public class ReadFromSystemIn {
public static void main(String[] args) {
try {
InputStreamReaderinputStreamReader = new InputStreamReader(Sys-
[Link]);
BufferedReaderbufferedReader = new BufferedReader(inputStream-
Reader);
[Link](“Enter your name:”);
String name = [Link]();
[Link](“Hello, “ + name + “!”);
[Link]();
} catch (IOException e) {
[Link]();
}
}
}

06
In the example above, [Link] is wrapped with InputStreamReader and then
with BufferedReader to read input as lines of text. The user is prompted to enter
NOTES
their name, and the program reads it from [Link] and displays a greeting.

[Link]
This is the standard error stream that is used to
output all the error data that a program might STUDY NOTE
throw, on a computer screen or any standard By default, [Link] is
output device. displayed in the console
with a different colour or
In Java, [Link] is an output stream
formatting to distinguish
typically used for error reporting and displaying
it from standard output.
error messages. It offers a mechanism to output
information about errors to the console or other
destinations and is an instance of the PrintStream class.

The purpose of [Link] is to separate error messages from regular output


produced by the program. By convention, error messages sent to [Link]
are displayed in a different colour or style in the console, making them visually
distinguishable from normal output.

Unlike [Link], which is the standard output stream, [Link] is typically


used for displaying error diagnostics, stack traces, or other critical information
related to program failures or exceptional conditions.

Consider the program:


public class SystemErrExample {
public static void main(String[] args) {
[Link](“An error occurred!”);
[Link](“This is an error message.”);
[Link](“Please check your input.”);
int numerator = 10;
int denominator = 0;
try {
int result = numerator / denominator;
[Link](“Result: “ + result);
} catch (ArithmeticException e) {
[Link](“Error: Division by zero”);
}
}
}

In the example above, we use [Link]() to print error messages


to the standard error stream. The program intentionally tries to divide a number
by zero, resulting in an ArithmeticException. The catch block catches the
exception, and the error message “Error: Division by zero” is printed to System.
err.

07
NOTES CHECK YOUR PROGRESS
4. [Link] and [Link] are two separate output streams in Java.
[True/False]
5. [Link] is used for reading data from the standard output stream.
[True/False]
6. [Link] is typically used for printing ____________ messages and
diagonistic information.

Activity
Research and analyse the usage and benefits of [Link] in Java for error
handling and debugging. Explore various techniques for utilizing Syste,.err
effectively and investigate real-world examples where it is used. Present your
finding s and discuss best practices for error reporting and debugging using
[Link].

6.4
Byte-oriented Streams

Byte-oriented streams are utilized to manage binary data input and output between
the Java program and the underlying system or files. These streams work with the
individual bytes, making them suitable for handling raw data, such as images, audio
files, or other non-textual data. There are several classes for byte-oriented streams
provided by the [Link] package.

File class
A mechanism to interact with files and directories in the file system is made possible
by Java’s File class, which is a component of the [Link] package. It represents a
file or directory path and offers various methods to perform operations such as
creating, deleting, renaming, and querying files and directories. Let’s go through
few examples:

Creating a File object:


You must first create a File object that represents the file or directory to interact
with it. The file or directory path can generate a File object as a string.

import [Link];
public class FileExample {
public static void main(String[] args) {

08
// File path for a file
String filePath = “C:\\myfolder\\[Link]”;
NOTES
// Creating a File object for the file path
File file = new File(filePath);
// File path for a directory
String dirPath = “C:\\myfolder”;
// Creating a File object for the directory path
File directory = new File(dirPath);
}
}

Deleting a file or directory:


The delete () method allows you to remove a file, and it also allows you to remove
an empty directory. However, to delete a directory along with its contents, you
should use the delete() method from the [Link] class.

import [Link];
public class FileExample {
public static void main(String[] args) {
String filePath = “C:\\myfolder\\[Link]”;
File file = new File(filePath);
if ([Link]()) {
[Link](“File deleted successfully!”);
} else {
[Link](“Failed to delete the file.”);
}
String dirPath = “C:\\myfolder\\emptydirectory”;
File directory = new File(dirPath);
if ([Link]()) {
[Link](“Empty directory deleted successfully!”);
} else {
[Link](“Failed to delete the directory.”);
}
}
}

Renaming a file or directory:You can rename a file or directory using the renameTo()
method.

InputStream class
An input stream in Java is a sequence of bytes that can be read from a source. The
source can be a file, an array, a peripheral device, or a socket.

All input streams in Java belong to the abstract superclass known as InputStream.
It provides a number of methods for reading data from the stream, such as:
● read(): Reads the stream’s subsequent byte of data.
● read(byte[]): Stores the number of bytes to be read from the stream in an
array.

09
NOTES ● available(): The number of bytes that can be read from the stream is returned
by the available() function.
● close(): Closes the stream and releases any resources it utilized from the
system.

There are a number of subclasses of InputStream that are specialized for reading
data from different types of sources. Some of the most commonly used subclasses
include:
● FileInputStream: Reads data from a file.
● ByteArrayInputStream: Reads data from an array of bytes.
● BufferedInputStream: Performs data reading and buffering from another input
stream, which may enhance performance.

Constructing an instance of the proper subclass would be best before using an


input stream. Then, you may read data from the stream using the methods of the
InputStream class.

Fig 2: Input Java Stream Classes

FileInputStreamclass
The FileInputStream class reads byte-oriented data (streams of raw bytes) such
as image data, audio data, video data, etc. from files. Commonly used methods
available in FileInputStream

● FileInputStream(String name) or FileInputStream(File file): These are the


constructors of the FileInputStream class. They create a new FileInputStream
object by opening a connection to the specified file.
● int read (): This method reads a single byte of data from the input stream and
returns the byte as an integer value (0-255). If the end of the file is reached, it
returns -1.
● int read (byte [] buffer): This method reads up to [Link] bytes of data
from the input stream into the specified byte array buffer. It returns the total
number of bytes read, or -1 if the end of the file is reached.

10
● int read (byte [] buffer, int offset, int length): This method reads up to length
bytes of data from the input stream into the specified byte array buffer, starting
NOTES
at the specified offset offset. It returns the total number of bytes read, or -1 if
the end of the file is reached.
● long skip (long n): This method skips over and discards n bytes of data from
the input stream. It returns the actual number of bytes skipped.
● int available (): This method returns an estimate of the number of bytes that
can be read from the input stream without blocking. It can be used to check the
amount of data available for reading.
● void close (): This method closes the input stream and releases any system
resources associated with it. It is good practice to call this method when you
are done reading from the file.

Consider the following program:


import [Link];
import [Link];
import [Link];
public class FileInputStreamExample {
public static void main (String [] args) {
// Specify the path of the file to be read
String filePath = “path/to/[Link]”;
try (FileInputStreamfis = new FileInputStream(filePath))
{
int byteData;
while ((byteData = [Link]()) != -1) {
[Link]((char) byteData);
}
} catch (IOException e) {
[Link]();
}
}
}

In the previous example, the path to the file to be read is used to build a
FileInputStream object. We read the file byte by byte using the read() method of
FileInputStream inside a try-with-resources block. When the file’s end is reached,
the procedure returns -1 instead of an integer value for each read byte.
Using (char) byteData, we transform each byte to its matching character
representation and print the result to the terminal. As a result, we can interpret the
file as a series of characters. Up until the file’s end, the loop keeps running. To read
data in bulk or skip a certain number of bytes, you can use the FileInputStream’s
other methods, such as read(byte[] buffer), read(byte[] buffer, int offset, int length),
and skip(long n).

OutputStream class
A series of bytes that can be written to a destination is referred to as a “output
stream” in Java. The destination can be a file, an array, a peripheral device, or a
socket.
11
NOTES All output streams in Java belong to the abstract superclass known as OutputStream.
It offers a variety of techniques for adding data to the stream, including:

● write(byte): Writes a single byte of data to the stream.


● write(byte[]): Writes a specified number of bytes to the stream.
● flush(): Forces any buffered data to be written to the stream.
● close():Closes the stream and releases any resources the system may have
been using for it.

There are a number of subclasses of OutputStream that are specialized for


writing data to different types of destinations. Some of the most commonly used
subclasses include:

● FileOutputStream: Writes data to a file.


● ByteArrayOutputStream: Writes data to an array of bytes.
● BufferedOutputStream: Performs data writing and buffering to another output
stream, which can enhance performance.

It would help if you first constructed an instance of the relevant subclass before
using an output stream. Then, you may write data to the stream using the methods
of the OutputStream class.

Fig 3: Output Java Stream Classes

FileOutputStream class
There are several ways to write data to a file using the Java FileOutputStream
class, an OutputStream subclass. There are a few frequently used methods in the
FileOutputStream class, including:

● FileOutputStream(String name) or FileOutputStream(File file): These are


the constructors of the FileOutputStream class. They open a connection to the
desired file for writing and then create a new FileOutputStream object.
● void write(int b): This method writes a single byte of data to the output stream.
The byte to be written is specified as the integer b, which represents the byte
value. Only the lowest 8 bits of the integer are written to the stream.

12
● void write(byte[] buffer): This method writes the entire byte array buffer to the
output stream.
NOTES
● void write(byte[] buffer, int offset, int length): This method writes a portion
of the byte array buffer to the output stream, starting from the specified offset
offset and writing length bytes.
● void flush(): This method flushes the output stream, ensuring that any buffered
data is written to the file immediately. It is good practice to call this method
when you want to make sure all the data is written.
● void close(): This method closes the output stream and releases any system
resources associated with it. It is important to call this method when you are
done writing to the file.

Example:
import [Link];
import [Link];
import [Link];
public class FileOutputStreamExample {
public static void main(String[] args) {
// Specify the path of the file to be written
String filePath = “path/to/[Link]”;
String data = “Hello, World!”;
try (FileOutputStreamfos = new FileOutputStream(file-
Path)) {
// Convert the string to bytes and write to the file
byte[] byteData = [Link]();
[Link](byteData);
[Link](“Data written to the file.”);
} catch (IOException e) {
[Link]();
}
}
}

In the example above, we create a FileOutputStream object fos by providing


the path of the file to be written. Inside a try-with-resources block, we convert the
string data to bytes using getBytes() and write the byte data to the file using the
write(byte[] buffer) method of [Link] writing the data,
we print a message indicating that the data has been written to the file.

CHECK YOUR PROGRESS


7. InputStream is used for reading data from a file, while FileInputStream
is used for reading data from other input sources.
8. The InputStream class provides a basic ___________ for reading data from
various sources.
9. Can FileInputStream be used to read data from a network connection?

13
NOTES 6.5
Character-oriented Classes

In Java, character-oriented reader and writer classes are essential components of


the I/O (Input/Output) system. They provide a convenient way to read and write
character-based data, such as text files, in a platform-independent manner. These
classes are utilized in Java’s file processing.

FileReaderclass
Data is read from files using the Java FileReader class. Like the FileInputStream
class, it returns data in byte [Link] is a character-oriented class that Java
programmers use to handle files.

To use the FileReader class, you need to follow these steps:


● Create an instance ofFileReader by providing the path of the file to be read as
a constructor argument.
● Use the various methods available in FileReader to read characters from the
file.
● Close the FileReader using the close() method to release system resources
associated with it.

Example:
import [Link];
import [Link];
public class FileReaderExample {
public static void main(String[] args) {
String filePath = “path/to/[Link]”;
try (FileReaderfileReader = new FileReader(filePath)) {
int character;
while ((character = [Link]()) != -1) {
[Link]((char) character);
}
} catch (IOException e) {
[Link]();
}
}
}

In the example above, we create a FileReader object fileReader by providing


the path of the file to be read. Inside a try-with-resources block, we read characters
from the file using the read() method of FileReader. When the file’s end is
reached, the read() method returns -1 instead of an integer indicating the read
character. We then print each character to the console by casting it to a char
using (char) character. This converts the integer value of the character to its
corresponding character representation.
14
FileWriter class
NOTES
The Java FileWriter class is used to write character-oriented data to files. Java
programmers use this character-oriented class to manage [Link] extends the
OutputStreamWriter class and provides methods to write characters to a file in a
sequential manner.

To use the FileWriter class, you need to follow these steps:


● Create an instance of FileWriter by providing the path of the file to be written
as a constructor argument.
● Use the various methods available in FileWriter to write characters to the file.
● To flush any leftover buffered data and free up system resources, close the
FileWriter using the close() method.

Example
import [Link];
import [Link];
public class FileWriterExample {
public static void main(String[] args) {
String filePath = “path/to/[Link]”;
try (FileWriterfileWriter = new FileWriter(filePath)) {
String text = “Hello, World!”;
[Link](text);
[Link](“Data written to the file successfully!”);
} catch (IOException e) {
[Link]();
}
}
}

In the previous example, the path to the file to be written is used to create the
FileWriter object fileWriter. We use the write() method of FileWriter inside a try-
with-resources block to write the string “Hello, World!” to the file.

The specified string is written to the file using the write() method. It makes a
new file if the file doesn’t already exist. If the file already exists, the new data
replaces its contents. To append data to an existing file, you can use the overloaded
constructor of FileWriter and pass true as the second argument.

Other commonly used methods in FileReader and FileWriter classes are:

Methods available in FileReader:


● read(char[] buffer): This method reads a section of text from a file into the
character array ‘buffer’ that is supplied. If the file’s end has been reached, it
gives -1 instead of the number of characters read.
● read(char[] buffer, int offset, int length): This function reads up to ‘length’
characters into the character array ‘buffer’ supplied by the caller, beginning at
the specified ‘offset’ index. If the file’s end has been reached, it gives -1 instead
of the number of characters read.

15
NOTES Methods available in FileWriter:
● write(int c): This method writes a single character specified by the integer `c`
to the file. The integer represents the character’s Unicode value.
● write(char[] buffer): This method writes an entire character array `buffer` to the
file.
● write(char[] buffer, int offset, int length): This method writes a portion of the
character array `buffer` to the file, starting at the specified `offset` index and
writing `length` characters.
● write(String str): This method writes the specified string str to the file.
● flush(): This method flushes any buffered characters to the file. It ensures that
all data is written to the file immediately.
● close(): This method closes the FileWriter, releasing system resources
associated with it. It is important to call this method when you finish writing to
the file.

CHECK YOUR PROGRESS


10. FileReader and FileWriter automatically handle character encoding in Java.
 [True/False]
11. Why do you think it is necessary to call the close() method after using
FileReader and FileWriter?

6.6
Buffered Streams

Buffered streams in Java are a set of classes


that provide an additional layer of buffering on STUDY NOTE
top of the basic byte or character streams. These Java supports chaining
buffered streams are designed to improve I/O of buffered streams.
performance by reducing the number of I/O This chaining of streams
operations performed on the underlying stream. can provide additional
performance benefits by
Benefits of Buffered Streams
optimizing data transfer
● Improved Performance: Buffered streams between different layers
reduce the overhead of frequent I/O of buffering.
operations by reading or writing data in larger
chunks. This can significantly enhance the
overall performance of your program, especially when dealing with large files
or network communication.

16
● Reduced System Calls: By using buffering, the number of system calls made
to read or write data is reduced, leading to more efficient I/O operations.
NOTES
● Automatic Data Caching: Buffered streams automatically cache data in
memory, making subsequent read or write operations faster. This is especially
useful when performing operations that involve repeated reading or writing,
such as reading lines from a file or writing chunks of data to a network socket.

Java Buffered Stream Classes


Java provides buffered stream classes for both byte-oriented and character-
oriented I/O operations:

BufferedInputStream and BufferedOutputStream:


These classes provide buffered operations for reading and writing binary data using
byte streams. BufferedInputStream reads data from an underlying InputStream,
while BufferedOutputStream writes data to an underlying OutputStream.

The BufferedInputStream class is used to read data from an input stream with
buffering support. It extends the FilterInputStream class. The buffering
helps reduce the number of disk or network operations, resulting in improved
performance.

Commonly Used Methods in BufferedInputStream:


● read(): Reads a byte of data from the buffered input stream and returns it as
an integer value.
● read(byte[] buffer): Reads bytes from the buffered input stream into the
provided byte array buffer and returns the number of bytes read.
● skip(long n): Skips over and discards n bytes of data from the buffered input
stream.
● available(): Returns an estimate of the number of bytes that can be read from
the buffered input stream without blocking.

Example:
Reading from a file using BufferedInputStream

try (BufferedInputStreaminputStream = new BufferedInput-


Stream(new FileInputStream(“[Link]”)))
{
int data; while ((data = [Link]()) != -1)
       {// Process the data [Link]((char) data);
       }
  } catch (IOException e)
    {
[Link]();
}

The code is wrapped in a try, which ensures that the BufferedInputStream is


closed automatically after its usage. Inside the try block, a BufferedInputStream
object named inputStream is created by wrapping a FileInputStream object. The

17
NOTES FileInputStream is created by passing the file path “[Link]” as a parameter
to its constructor. This establishes a connection between the program and the file
for reading.

The code enters a while loop, which continues until the read() method of
inputStream returns -1. The read() method reads a single byte from the file and
returns its value as an integer. When the end of the file is reached, the read()
method returns -[Link] the while loop, the code processes the read byte of data.
In this case, the code simply prints the character representation of the read byte
by typecasting data to a char using (char) data. This prints the content of the file
character by [Link] reading and processing all the characters in the file,
the BufferedInputStream is closed automatically. This ensures that any system
resources associated with the file are released.

If any IOException occurs during the file reading process, the catch block is
executed. The exception is caught, and its stack trace is printed to the console
using [Link]().Therefore, when you run this code and assuming
the file “[Link]” contains the text “Hello, World!”, the output will be:

Hello World!

The code reads each character from the file and prints it to the console, resulting in
the complete content of the file being displayed.

The BufferedOutputStream class is used to write data to an output stream


with buffering support. It extends the FilterOutputStream class. The buffering
helps reduce the number of disk or network operations, resulting in improved
performance.

Commonly Used Methods in BufferedOutputStream:


● write(int b): Writes the specified byte `b` to the buffered output stream.
● write(byte[] buffer): Writes the contents of the byte array `buffer` to the
buffered output stream.
● flush(): Flushes the buffered output stream, forcing any buffered bytes to be
written to the underlying output stream.
● close(): Closes the buffered output stream and releases any system resources
associated with it.

Example:
import [Link];
import [Link];
import [Link];
public class BufferedOutputStreamExample {
public static void main(String[] args) {
try (BufferedOutputStreambufferedOutputStream = new
BufferedOutputStream(new FileOutputStream(“path/to/[Link]”)))
{
String text = “Hello, World!”;
[Link]([Link]());

18
[Link]();
[Link](“Data written to the file successfully!”);
NOTES
} catch (IOException e) {
[Link]();
}
}
}

BufferedReader and BufferedWriter


These classes provide buffered operations for reading and writing text-based data
using character streams. BufferedReader reads data from an underlying Reader,
while BufferedWriter writes data to an underlying Writer.

Example:
Reading from a file using BufferedReader

try (BufferedReader reader = new BufferedReader(new FileRead-


er(“[Link]”)))
{
    String line; while ((line = [Link]()) != null)
        { // Process the line [Link](line);
        }
  } catch (IOException e)
{[Link]();
}

The code is wrapped in a try statement, which ensures that the BufferedReader
is closed automatically after its usage. Inside the try block, a BufferedReader
object named reader is created by wrapping a FileReader object. The FileReader
is created by passing the file path “[Link]” as a parameter to its constructor.
This establishes a connection between the program and the file for reading.

The code enters a while loop, which continues until the readLine() method of
reader returns null. The readLine() method reads a single line from the file and
returns it as a String. When the end of the file is reached, the readLine() method
returns [Link] the while loop, the code processes the read line of data. In this
case, the code simply prints the line to the console using [Link](line).
After reading and processing all the lines in the file, the BufferedReader is closed
automatically due to the try-with-resources statement. This ensures that any
system resources associated with the file are released.

If any IOException occurs during the file reading process, the catch block is
executed. The exception is caught, and its stack trace is printed to the console
using [Link]().

Therefore, when you run this code and assuming the file “[Link]” contains
the following lines:

Hello, World!

Welcome to JavaTpoint.

19
NOTES The output will be:

Hello, World!
Welcome to JavaTpoint.
The code reads each line from the file and prints it to the console, resulting in the
complete content of the file being displayed line by line.
The BufferedWriter class is used to write text data to a character output stream
with buffering support, which improves performance by reducing the number of
disk or network operations. It extends the `Writer` class.

Example:
import [Link];
import [Link];
import [Link];
public class BufferedWriterExample {
public static void main(String[] args) {
try (BufferedWriterbufferedWriter = new BufferedWrit-
er(new FileWriter(“path/to/[Link]”))) {
String text = “Hello, World!”;
[Link](text);
[Link]();
[Link](“This is a new line.”);
[Link]();
[Link](“Data written to the file successfully!”);
} catch (IOException e) {
[Link]();
}
}
}

The program writes text data to a file using a BufferedWriter. The write() method
writes the specified string to the buffered writer. The newLine() method writes a
platform-specific line separator. The flush() method flushes any buffered characters
to the underlying output stream, ensuring that the data is written immediately. The
program then prints a success message to the console.

DataInput and DataOutput Streams using Buffered classes


The DataOutputStream and DataInputStream classes in Java provide
functionality for reading and writing primitive data types to/from a stream. These
classes allow you to read and write data in a platform-independent manner, as the
data is converted into a binary representation.
When used in conjunction with buffered streams, the performance can be improved
by reducing the number of disk or network operations.

DataOutputStream with BufferedWriter:


The DataOutputStream class allows you to write primitive data types and binary
data. When combined with BufferedWriter, you can write text data in a specific
format while using the write methods of DataOutputStream.
20
Example:
try (DataOutputStream dos = new DataOutputStream(new Buffered-
NOTES
OutputStream(new FileOutputStream(“[Link]”)));
BufferedWriterbw = new BufferedWriter(new OutputStreamWriter(-
dos))) {
String line = “Example Line”;
int value = 100;
[Link](line);
[Link]();
[Link](value);
} catch (IOException e) {
[Link]();
}

In this example, we use DataOutputStream with BufferedWriter to write data


to a file named “[Link]”. The BufferedWriter writes the text line, and the
DataOutputStream writes the integer value using the writeInt() method.
DataInputStream with BufferedReader:
The DataInputStream class allows you to read primitive data types and binary data.
By combining it with BufferedReader, you can read text data line by line and parse
the necessary values using the appropriate read methods of DataInputStream.

Example:
try (DataInputStream dis = new DataInputStream(new BufferedIn-
putStream(new FileInputStream(“[Link]”)));
BufferedReaderbr = new BufferedReader(new InputStreamRead-
er(dis))) {
// Read the string data
String line = [Link]();
[Link](“Read Line: “ + line);
// Read the integer data
int value = [Link]();
[Link](“Read Value: “ + value);
} catch (IOException e) {
[Link]();
}
In this example, we use DataInputStream with BufferedReader to read data from
the same file named “[Link]”. The BufferedReader reads the text line, and the
DataInputStream reads the integer values using the readInt() method.

CHECK YOUR PROGRESS


12. BufferedInputStream and BufferedOutputStream classes provide
___________ support for input and output streams, respectively.
13. BufferedStreams help reduce the number of ___________ operations,
improving performance.
14. DataInputStream and DataOutputStream can read and write primitive data
types in a platform-independent manner.
21
NOTES Activity
Conduct research on the efficiency of BufferedInputStream and
BufferedOutputStream. Compare the performance of buffered streams with
regular streams for reading and writing large files. Measure factors such as
execution time and memory usage, analyse the results and present your findings
on efficiency gains achieved with BufferedStreams.

6.7
Serialization and Deserialization

An object is transformed into a byte stream


through the serialization process, which can then STUDY NOTE
be stored in a file, sent over a network, or stored Java serialization
in a database. The opposite of recreating the supports cyclic object
object from the byte stream is deserialization. graphs, where objects
reference each
The Serializable interface, a marker interface
other, by maintaining
without any methods, is implemented in Java
object identity during
to achieve [Link] marking a class as
serialization and
Serializable, you indicate that its objects can be
deserialization.
serialized and deserialized.

Serialization and deserialization allow objects to


be persisted and transferred across different systems or platforms, making it a
useful feature in various scenarios such as data storage, network communication,
and distributed systems.

Benefits of Serialization:
● Object Persistence: Serialization allows objects to be stored in a serialized
form, which can be written to a file, a database, or sent over a network. By
implementing the Serializable interface, you can make your objects persistable,
enabling long-term storage and retrieval of object data.
● Network Communication: Serializable objects can be easily serialized and
deserialized, making them suitable for network communication. Objects can
be serialized and sent across a network to remote systems or other Java
applications, allowing for efficient data exchange.
● Distributed Systems: Serializable objects are crucial in distributed systems,
where objects may need to be transferred between different machines or
processes. By serializing objects, you can seamlessly transport them across
different platforms or systems, ensuring consistency in data representation.
22
● Caching and Performance: Serializable objects can be cached, improving
application performance. By serializing and deserializing objects, you can store
NOTES
them in memory or disk cache, reducing the need to recreate or recompute
objects. This can lead to significant performance improvements in applications
that deal with large or complex object graphs.
● Deep Copy and Cloning: Serialization can be used to create deep copies of
objects by serializing and deserializing them. This is particularly useful when
you need to create independent copies of complex objects or object graphs.
● Framework Integration: Many Java frameworks and libraries rely on object
serialization to provide additional functionality. By implementing the Serializable
interface, your objects can seamlessly integrate with these frameworks,
allowing you to take advantage of their features and capabilities.

Using object streams in Java, specifically ObjectOutputStream and


ObjectInputStream, simplifies the process of serializing and deserializing
objects. These streams handle the serialization and deserialization of entire object
graphs, including their associated data and relationships.

Serialization with ObjectOutputStream:


To serialize an object using ObjectOutputStream, follow these steps:
● Create an instance of ObjectOutputStream by passing an underlying output
stream, such as FileOutputStream or [Link]().
● Use the writeObject() method of the ObjectOutputStream to write the object
to the stream.

Example:
import [Link];
import [Link];
import [Link];
public class SerializationExample {
public static void main(String[] args) {
try (FileOutputStreamfileOutputStream = new FileOutput-
Stream(“[Link]”);
ObjectOutputStreamobjectOutputStream = new ObjectOutputStream(-
fileOutputStream)) {
Person person = new Person(“John Doe”, 30);
[Link](person);
[Link](“Serialization completed. Object saved to
[Link]”);
} catch (Exception e) {
[Link]();
}
}
}
class Person implements Serializable {
private String name;
private int age;

23
NOTES public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
// Getters and setters
}

In this example, we create an instance of Person and serialize it using


ObjectOutputStream. The Person class implements the Serializable
interface to indicate that its objects can be serialized.

Deserialization with ObjectInputStream:


To deserialize an object using ObjectInputStream, follow these steps:
● Create an instance of ObjectInputStream by passing an underlying input stream,
such as FileInputStream or [Link]().
● Use the readObject() method of the ObjectInputStreamto read the object from
the stream. Cast the returned object to the appropriate class.

Example:
import [Link];
import [Link];
public class DeserializationExample {
public static void main(String[] args) {
try (FileInputStreamfileInputStream = new FileInput-
Stream(“[Link]”);
ObjectInputStreamobjectInputStream = new ObjectInputStream(file-
InputStream)) {
Person deserializedPerson = (Person) objectInput-
[Link]();
[Link](“Deserialization completed. Object loaded
from [Link]”);
[Link](“Name: “ + [Link]());
[Link](“Age: “ + [Link]());
} catch (Exception e) {
[Link]();
}
}
}

In this example, we deserialize the serialized Person object from the file “person.
ser” using ObjectInputStream. The deserialized object is cast to the `Person`
class, and its properties are printed to the console.

CHECK YOUR PROGRESS


15. All the classes in Java can be serialized by default. [True/False]
16. During deserialization, the ___________ method is invoked to read the object
from the input stream.

24
6.8 NOTES
Summary

● Java Input/Output (I/O) is a mechanism for reading and writing data to and from
external sources such as files, network connections, and databases.
● The two main types of streams in Java I/O are byte streams and character
streams. Byte streams are used for reading and writing binary data, while
character streams are used for reading and writing text data.
● Byte streams, such as FileInputStream and FileOutputStream, are used for
processing binary data.
● Character streams, such as FileReader and FileWriter, are used for processing
character-based data, such as text files.
● Streams in Java are a sequence of data elements that can be processed in a
declarative and functional manner.
● The [Link] stream is used for standard output, allowing programs
to produce results on an output device like a computer screen. It provides
methods like print() and println() for displaying text.
● The [Link] stream is used for standard input, allowing programs to read
characters from the keyboard or other input devices.
● The [Link] stream is used for error reporting and displaying error messages
● Streams can be used for file I/O, network I/O, and other I/O operations in Java.
● An input stream in Java is a sequence of bytes that can be read from a source
like a file, array, peripheral device, or socket.
● The InputStream class is the abstract superclass of all input streams in Java.
● FileInputStream is a subclass of InputStream used for reading data from files.
● An output stream in Java is a sequence of bytes that can be written to a
destination like a file, array, peripheral device, or socket.
● The OutputStream class is the abstract superclass of all output streams in Java.
● FileOutputStream is a subclass of OutputStream used for writing data to files.
● FileReader class is used to read character-oriented data from files.
● Methods of FileReader class include read() to read a character and close() to
close the FileReader object.
● FileWriter class is used to write character-oriented data to files.
● Serialization in Java allows you to save an object’s state as a byte stream.
● Deserialization is the process of transforming a byte stream back into an object.
● Serialization and deserialization are platform-independent processes and can
be done on different platforms.

25
NOTES 6.9
Case Study

Implementation of payment processing systems by the National Payments


Corporation of India (NPCI)
NPCI is an organization that operates various retail payment systems in India,
including the Unified Payments Interface (UPI).

In their payment processing systems, NPCI utilizes Java I/O to handle the input and
output streams involved in transaction processing. The systems handle a massive
volume of real-time transactions across multiple banks and payment service
providers.

By leveraging Java I/O, NPCI ensures efficient and reliable data transfer between
the various components of their payment processing infrastructure. Java I/O’s
capabilities in handling byte streams, character streams, buffering, and serialization/
deserialization enable NPCI to effectively process and route payment transactions
while ensuring data integrity and security.

The implementation of Java I/O in NPCI’s payment processing systems showcases


how the powerful I/O capabilities of Java are leveraged in real-world, high-volume
transactional applications, facilitating seamless and secure payment experiences
for millions of users across India.

Questions:
1. How does NPCI’s utilization of Java I/O in their payment processing systems
contribute to efficient and reliable data transfer in real-time transactions?
Discuss the specific capabilities of Java I/O that enable NPCI to handle the
input and output streams effectively.
2. Explore the significance of Java I/O’s buffering and serialization/deserialization
capabilities in NPCI’s payment processing systems. How do these features
contribute to data integrity and security while processing and routing payment
transactions across multiple banks and payment service providers?

6.10
Terminal Questions

SHORT ANSWER QUESTIONS


1. How does versioning and compatibility play a role in object serialization and

26 deserialization?
2. What are the alternatives to Java’s built-in serialization for object persistence?
NOTES
3. How does buffering improve the performance of writing data to a file using
BufferedWriter?

LONG ANSWER. QUESTIONS


1. Discuss the concept of character encoding and decoding in Java I/O. Explain
the role of InputStreamReader and OutputStreamWriter in converting byte
streams to character streams and vice versa, considering different character
encodings.
2. Write a Java program that reads a text file using a character stream, counts the
occurrences of each word, and displays the word count in descending order.

MULTIPLE CHOICE QUESTIONS


1. Which of the following statements is true regarding byte streams in Java?
a) Byte streams are suitable for handling both character and binary data.
b) Byte streams are more efficient than character streams for reading textual
data.
c) 
Byte streams provide better internationalization support compared to
character streams.
d) Byte streams are not capable of handling Unicode characters.
2. What is the advantage of using character-oriented classes (e.g., BufferedReader,
BufferedWriter) over byte-oriented classes (e.g., FileInputStream, FileOutputStream)
in Java I/O?
a) Character-oriented classes provide better performance for large data sets.
b) Character-oriented classes can handle binary data more efficiently.
c) Character-oriented classes offer higher-level abstractions for working with
textual data.
d) 
Character-oriented classes are more secure compared to byte-oriented
classes.
3. Which class is used to handle file-related operations, such as creating, deleting,
and renaming files, in Java?
a) File b) FileInputStream
c) FileOutputStream d) FileWriter
4. What is the purpose of the [Link] stream in Java?
a) It is used for reading input from the console.
b) It is used for standard error output.
c) It is used for writing binary data.
d) It is used for standard output.
5. Which class is used for reading text from a character stream in Java?
a) FileReader b) FileWriter
c) InputStreamReader d) OutputStreamWriter

27
NOTES 6. Which class is used for writing text to a character stream in Java?
a) FileReader b) FileWriter
c) InputStreamReader d) OutputStreamWriter
7. Which class is used for reading and writing primitive data types and binary data
in Java?
a) InputStream b) OutputStream
c) DataInputStream d) DataOutputStream
8. Which class is used for serialization in Java?
a) ObjectInputStream b) ObjectOutputStream
c) BufferedReader d) BufferedWriter
9. Which class is used for reading text from a character stream with buffering in
Java?
a) BufferedReader b) BufferedWriter
c) FileReader d) FileWriter
10. Which class is used for writing text to a character stream with buffering in Java?
a) BufferedReader b) BufferedWriter
c) FileReader d) FileWriter
11. You need to read a large text file and process it line by line in Java. Which
stream or class would you use for efficient reading of the file?
a) FileInputStream b) FileReader
c) BufferedReader d) InputStreamReader
12. You want to write binary data to a file in Java. Which stream or class would you
use for this purpose?
a) FileOutputStream b) FileWriter
c) BufferedOutputStream d) DataOutputStream
13. You are developing a program that requires user input from the console. Which
stream or class would you use to read user input?
a) [Link] b) [Link]
c) [Link] d) BufferedReader
14. You want to handle character data in a Java program and need to convert byte
streams to character streams. Which class would you use for this purpose?
a) BufferedReader b) BufferedWriter
c) InputStreamReader d) OutputStreamWriter
15. You want to append data to an existing text file in Java. Which stream or class
would you use to achieve this?
a) FileOutputStream b) FileWriter
c) BufferedOutputStream d) RandomAccessFile

28
6.11 NOTES
Answers

CHECK YOUR PROEGRESS


1. True 9. To be solved by student
2. OutputStreamWriter 10. False
3. InputStream 11. To be solve dby student
4. True 12. Buffering
5. False 13. Disk or network
6. Error or exception 14. True
7. False 15. False
8. Framework or abstraction 16. ReadObject()

SHORT ANSWER QUESTIONS


1. Versioning and compatibility are important considerations when working
with object serialization and deserialization. Versioning refers to managing
the compatibility between serialized objects and their class definitions when
changes are made to the class.
When a class is serialized, a unique identifier called serialVersionUID is assigned
to it. This identifier is used during deserialization to check the compatibility
between the serialized object and the class definition. If the serialVersionUID of
the serialized object does not match the serialVersionUID of the class definition,
an InvalidClassException is thrown.
To ensure versioning and compatibility, it is recommended to explicitly declare
a serialVersionUID for Serializable classes. By managing the serialVersionUID,
you can control the compatibility between different versions of the class. When
making changes to the class, such as adding or removing fields, it is important to
update the serialVersionUID accordingly to maintain compatibility. Additionally,
it is good practice to handle versioning issues gracefully, such as by providing
custom readObject() and writeObject() methods to handle different versions of
the class.
2. While Java’s built-in serialization provides a convenient way to serialize and
deserialize objects, there are alternative approaches for object persistence:
● Externalization: The Externalizable interface can be implemented
instead of Serializable to have more control over the serialization process.
Externalizable allows custom serialization and deserialization logic by
implementing the readExternal() and writeExternal() methods.
● JSON/XML Serialization: Instead of using Java’s binary serialization,
objects can be serialized to JSON or XML formats. Libraries like Jackson
or Gson can be used to convert objects to JSON or XML representations,
which can be easily stored, transmitted, or shared across different platforms.
29
NOTES ● Database Persistence: Instead of serializing objects to files, object
persistence can be achieved by storing them in a database. Object-relational
mapping (ORM) frameworks like Hibernate or JPA provide mechanisms to
map objects to relational database tables and perform CRUD operations.
3. Buffering Enhances File Writing Performance with BufferedWriter
Buffering, in the context of file writing using Java’s BufferedWriter, significantly
improves performance by reducing the number of actual write operations and
optimizing data transfer.
● Minimized I/O Operations: Buffering groups data into a temporary
memory buffer before writing it to the file. This reduces the frequency of
individual write operations, as multiple data chunks are written together in
one go.
● Reduced Overhead:Buffering decreases the overhead associated with
invoking the operating system’s file writing routines. This overhead reduction
is particularly noticeable when writing small pieces of data.
Java BufferedWriter Example:
In Java, using a BufferedWriter is straightforward. By wrapping it around another
Writer, like a FileWriter, you create a buffering effect. For instance:
try (BufferedWriter writer = new BufferedWriter(new FileWriter(“[Link]”))) {
[Link](“Hello, Buffering!”);
// More write operations...
} catch (IOException e) {
[Link]();
}

In conclusion, buffering in BufferedWriter optimizes file writing by minimizing I/O


operations, enhancing data transfer efficiency, and reducing overhead. This leads
to notable performance improvements when dealing with file output in Java
applications.

LONG ANSWER QUESTIONS


1. Character encoding refers to the process of converting characters into bytes,
while decoding refers to converting bytes back into characters. In Java I/O, the
InputStreamReader and OutputStreamWriter classes play a crucial role in this
conversion process.
The InputStreamReader class is used to bridge the gap between byte streams
and character streams. It reads bytes from an underlying InputStream and
decodes them into characters using a specified character encoding. By
providing an appropriate character encoding, InputStreamReader can handle
different encodings such as UTF-8, ISO-8859-1, and more.
The OutputStreamWriter class, on the other hand, converts characters into
bytes and bridges the gap between character streams and byte streams. It
writes characters to an underlying OutputStream and encodes them using a
specified character encoding. OutputStreamWriter allows you to specify the
desired encoding when writing character data to an output stream.
30
These classes facilitate the conversion between byte streams and character
streams, ensuring proper encoding and decoding, and allowing seamless
NOTES
handling of textual data in different character encodings.
2. import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class WordCountProgram {
public static void main(String[] args) {
// File path
String filePath = “path/to/[Link]”;
// Create a map to store word counts
Map<String, Integer>wordCountMap = new HashMap<>();
try (BufferedReader reader = new BufferedReader(new
FileReader(filePath))) {
String line;
while ((line = [Link]()) != null) {
// Split the line into words
String[] words = [Link](“\\s+”);
// Update the word count map
for (String word : words) {
[Link](word, [Link](word, 0)
+ 1);
}
}
} catch (IOException e) {
[Link]();
}
// Create a TreeMap to sort the word count map in
descending order
Map<String, Integer>sortedWordCountMap = new
TreeMap<>((w1, w2) -> {
int count1 = [Link](w1);
int count2 = [Link](w2);
// Sort by count in descending order
if (count1 != count2) {
return [Link](count2, count1);
}
// If counts are equal, sort lexicographically
return [Link](w2);
});
[Link](wordCountMap);
// Display the word count in descending order
for ([Link]<String, Integer>entry :sortedWord-
[Link]()) {
31
NOTES [Link]([Link]() + “: “ + [Link]-
ue());
}
}
}

MCQS ANSWERS
1. a) Byte streams are suitable for handling both character and binary data.
2. c) Character-oriented classes offer higher-level abstractions for working with
textual data.
3. a) File
4. d) It is used for standard output.
5. a) FileReader
6. b) FileWriter
7. c) DataInputStream
8. b) ObjectOutputStream
9. a) BufferedReader
10. b) BufferedWriter
11. c) BufferedReader
12. a) FileOutputStream
13. d) BufferedReader
14. c) InputStreamReader
15. b) FileWriter

6.12
Assignment

MULTIPLE CHOICE QUESTIONS


1. You want to read serialized objects from a file in Java. Which stream or class
would you use for this purpose?
a) ObjectInputStream b) ObjectOutputStream
c) DataInputStream d) FileReader
2. You need to write a large amount of text data to a file efficiently in Java. Which
class or stream would you use for this purpose?
a) FileWriter b) BufferedWriter
c) FileOutputStream d) PrintWriter

32
3. You want to read and write primitive data types and binary data in Java. Which
class or stream would you use for this purpose?
NOTES
a) InputStreamReader b) DataInputStream
c) BufferedReader d) DataOutputStream
4. You want to read a CSV file and parse its contents in Java. Which class or
stream would you use for efficient parsing and handling of the file?
a) FileInputStream b) FileReader
c) BufferedReader d) Scanner
5. You want to serialize an object and write it to a file in Java. Which stream or
class would you use for this purpose?
a) ObjectInputStream b) ObjectOutputStream
c) FileReader d) FileWriter

QUESTIONS
1. What are the advantages of using File Reader and File Writer over other file I/O
methods in Java?
2. How can File Reader and File Writer classes be used together with other Java
I/O classes to perform more advanced file operations?
3. Describe the concept of file handling in Java. Discuss the functionalities
provided by the File class, including creating, deleting, renaming, and navigating
directories, along with file permission management.
4. Create a Java program that serializes a collection of custom objects into a
file using object streams, then deserializes the objects and performs specific
operations on them (e.g., filtering, sorting, aggregation), and finally displays the
results.
5. Write a Java program that reads a directory path from the user, lists all the files
and subdirectories within the directory recursively, and displays their names,
sizes, and permissions.

6.13
References

Websites:
● [Link]
● [Link]
● [Link]
● [Link]
● [Link]
33

You might also like