0% found this document useful (0 votes)
1 views29 pages

MCA Lab On Java Programming Unit 6 Java Input Output

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)
1 views29 pages

MCA Lab On Java Programming Unit 6 Java Input Output

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

Lab on Java Programming

Java
Input/Output
SELF LEARNING MATERIAL

SEM - I (107)

MCA
UNIT-6 JAVA INPUT/OUTPUT
TABLE OF CONTENTS

6.1 Introduction
6.2 InputStream and OutputStream classes
6.3 Reading and Writing data into files
6.4 Use of console to read data
6.5 Using readers and writers to write data into files
6.6 Buffered Streams
6.7 Serialization
6.8 Summary
6.9 Case Study
6.10 Terminal Questions
6.11 Answers
6.12 Assignment
6.13 References

Learning Objectives
• To understand InputStream and OutputStream classes with programs
• To learn how to perform reading and writing data into files
• To write programs using Buffered Streams
NOTES

6.1
Introduction
Java Input and Output (I/O) is an essential concept that enables the reading
of data from external sources and the writing of data to external destinations.
It provides a consistent and unified approach to handle various types of I/O
operations.

The two main types of Java I/O are character streams and byte streams.

Byte Streams:
Byte streams are used for handling binary data, such as images, audio files,
or any non-textual data. The InputStream and OutputStream classes, which
serve as the cornerstone for reading and writing bytes, are the fundamental
elements of byte stream I/O.

Specific examples of byte stream subclasses include FileInputStream


and FileOutputStream for file I/O, ByteArrayInputStream and
ByteArrayOutputStream for in-memory operations, and SocketInputStream
and SocketOutputStream for network communication.

Character Streams:
Character streams are made for text-based operations including reading and
writing text files and string manipulation. The Reader and Writer classes,

01
NOTES which deal with character encoding/decoding and offer methods for reading
and writing characters or strings, are the key components of character stream
I/O.

Character stream subclasses encompass FileReader and FileWriter for text file
I/O, BufferedReader and BufferedWriter for improved performance through
buffering, and InputStreamReader and OutputStreamWriter for bridging byte
streams to character streams.

Java I/O also supports higher-level abstractions like object serialization (with
ObjectInputStream and ObjectOutputStream) for object persistence, as well
as utility classes such as Scanner for simplified input parsing and PrintWriter
for formatted output.

6.2
InputStream and OutputStream Classes

A stream is a collection of data that is continuously


flowing and can be characterized as a handy STUDY NOTE
approach to handle input and output activities. Java allows to use
InputStream and
The InputStream class is an abstract class in
OutputStream in
the Byte Stream hierarchy, specifically designed
combination with byte
for reading data. It can be utilized to read various
arrays or buffers to
types of data sources, such as files, images,
process data in smaller
audio, video, webpages, and more. Regardless of
portions, reducing
the specific type, an InputStream reads data from
memory usage and
the source incrementally, processing one item at
improving performance.
a time.

The OutputStream class is an abstract class in the Byte Stream hierarchy, serving
as a means for writing data. It is used to write data to destinations like files,
images, audio files, and so on. Similar to InputStream, an OutputStream performs
the writing process sequentially, handling one piece of data at a time.

Example:
import [Link].*;
public class StreamExample {
public static void main(String[] args) {
try {
// Create an input stream to read data from a file

02

FileInputStream inputStream = new FileInput-
Stream(“[Link]”);
NOTES
// Create an output stream to write data to a file

FileOutputStream outputStream = new FileOutput-
Stream(“[Link]”);
// 
Read data from the input stream and write it to
the output stream
int byteData;
while ((byteData = [Link]()) != -1) {
[Link](byteData);
}
// Close the streams
[Link]();
[Link]();

[Link](“Data has been copied from in-
[Link] to [Link].”);
} catch (IOException e) {

[Link](“An error occurred: “ + [Link]-
Message());
}
}
}

In the above program, within the try block, two streams are created:
FileInputStream and FileOutputStream. The FileInputStream is used to
read data from a file named “[Link]”, while the FileOutputStream is used to
write data to a file named “[Link]”. The code then enters a while loop, which
reads data from the input stream (inputStream) one byte at a time. The read()
method of FileInputStream returns the next byte of data, and if it reaches the
end of the stream, it returns -1. The loop continues until the end of the stream
is reached. Inside the loop, each byte of data is written to the output stream
(outputStream) using the write() method of FileOutputStream.

After the loop finishes, the input and output streams are closed using the close()
method. Closing the streams is important to release system resources and ensure
data is properly written. Finally, a message is printed to the console indicating
that the data has been successfully copied from “[Link]” to “[Link]”. If
an IOException occurs during the execution of the code (e.g., file not found,
permission issues), the exception is caught in the catch block. The error message
is printed to the console using the getMessage() method of the exception.

CHECK YOUR PROGRESS


1. InputStream writes data to the destination once at a time [True/False]
2. OutputStream is an abstract class that describes Stream Output[True/False]
3. public void write(byte[])throws IOException : is used to write
array of bytes to current output stream [True/False]

03
NOTES Activity
Create a Java program for File Copy Utility. Prompt the user to enter the source
file path and destination file path. The program should validate the existence of
the source file and handle any exception that may occur during file I/O operations.

6.3
Reading and Writing Data into Files

There are multiple approaches available for reading and writing text files in Java,
which are commonly utilized in various applications. When it comes to reading
plain text files, Java offers several methods such as FileReader, BufferedReader,
and Scanner. Each of these utilities provides unique features and capabilities.
For instance, BufferedReader facilitates data buffering for efficient reading, while
Scanner allows for convenient parsing.

Some of the common methods for reading text files in Java:


1. Utilizing the BufferedReader class.
2. Utilizing the Scanner class.
3. Utilizing the FileReader class.

In Java, it is also possible to combine BufferedReader and Scanner to read line by


line a text file. Additionally, Java SE 8 introduced the [Link] class,
which offers a lazy and more efficient approach to file reading.

It is important to select the appropriate method based on your specific requirements


and the nature of the text file. Remember to handle exceptions and close any
resources used to ensure proper resource management.

In Java, there exist numerous approaches for writing data into a file, as the language
offers various classes and methods to accomplish this task. Some of the common
methods for file writing include:
1. Utilizing the writeString() method.
2. Employing the FileWriter class.
3. Utilizing the BufferedWriter class.
4. Making use of the FileOutputStream class.

These methods provide different functionalities and can be chosen based on the
specific requirements of the file-writing task at hand. By leveraging these classes
and methods, developers have flexibility in selecting the most suitable approach for
their particular use case.

04
CHECK YOUR PROGRESS
NOTES
4. Mention the different ways to read a file in Java.
5. Reading data from a file refers to displaying records for users to see
[True/False]
6. There are different methods to read and write data depending upon their
distinctive functionalities [True/False]

6.4
Making Use of Console to Read Data

To read data from the console in Java, you can use the Scanner class.

import [Link];
public class ConsoleInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link](“Enter your name: “);
String name = [Link]();
[Link](“Enter your age: “);
int age = [Link]();
[Link](“Name: “ + name);
[Link](“Age: “ + age);
[Link]();
}
}

In this example, we create a Scanner object and pass [Link] as the


argument, which represents the standard input stream (console). We can then use
various methods of the Scanner class to read different types of input. Here, we use
nextLine() to read a line of text (name) entered by the user, and nextInt() to
read an integer (age) entered by the user.

The collected data is then printed to the console. It’s crucial to release any connected
resources by closing the Scanner using the close() method.

When you run this program, it will prompt you to enter your name and age in the
console. After entering the values, it will display the entered name and age.

05
NOTES CHECK YOUR PROGRESS
7. You are developing a command-line utility that requires the user to enter
their personal information. The utility needs to collect the user’s name, age,
and email address. You want to implement a feature where the user can
enter this information directly in the console. Write a Java program that uses
the console to read and display the user’s information.
8. The _______ method of the Console class is used to read a line of text entered
by the user from the console.

Activity
You are building a simple ticket booking system in Java. The program prompts
the user to enter their name, the number of tickets they want to purchase, and
the ticket price. You need to implement the code to read this input from the
console and calculate the total ticket cost. Write a Java code snippet that uses
the console to read the user’s name, number of tickets, and ticket price. Then,
calculate and display the total cost of the tickets.

6.5
Using Readers and Writers to
Write Data into Files

Reading data from a file


FileReader is a valuable utility for reading character data from a “text” file. It
is derived from the InputStreamReader class. The constructors of FileReader
by default assume the appropriate byte-buffer size and character encoding. If you
wish to specify your own values, you can construct an InputStreamReader on a
FileInputStream.

FileReader is specifically designed for reading character streams. If your


requirement involves reading streams of raw bytes, it is recommended to utilize a
FileInputStream instead.

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

06
FileReader fileReader = new FileReader(“[Link]”);
int data;
NOTES
while ((data = [Link]()) != -1) {
char character = (char) data;
[Link](character);
}
[Link]();
} catch (IOException e) {

[Link](“An error occurred: “ + e.
getMessage());
}
}
}

Here, we use the read() method of FileReader to read a single character from
the file. The read() method returns an integer value, which we assign to the
variable data. Inside the while loop, we check if data is not equal to -1, indicating
that there is still data to be read. If true, we cast data to a character and print it.

Writing data into a file


FileWriter is a convenient tool for creating
a file and writing characters into it. It is derived STUDY NOTE
from the OutputStream class. The constructors When using FileReader
of FileWriter by default take the proper character or FileWriter, it is
encoding and byte-buffer size. If you want to important to handle
specify your own values, you can construct an exceptions, such as
OutputStreamWriter on a FileOutputStream. IOException, that
may occur during file
FileWriter is specifically designed for writing
operations. Proper
character streams. If you need to write streams
exception handling
of raw bytes, it is recommended to use a
ensures graceful error
FileOutputStream instead. If the output file is
handling and resource
not already there, FileWriter immediately creates
cleanup.
it.

import [Link].*;
public class FileWriteExample {
public static void main(String[] args) {
try {
// Create a FileWriter object to write to a file
FileWriter writer = new FileWriter(“[Link]”);
// Write data to the file
[Link](“Hello, World!”);
[Link](“\n”);
[Link](“This is a sample file.”);
// Close the FileWriter
[Link]();

[Link](“Data has been written to
[Link].”);
07
NOTES } catch (IOException e) {

[Link](“An error occurred: “ + e.
getMessage());
}
}
}

In this example, we create a FileWriter object, which allows us to write data


to a file. Next, we write the required data into the file using the write() method. In
this case, we write the strings “Hello, World!” and “This is a sample file.” to the file
“[Link]”. Finally, we close the FileWriter to release any system resources.

When you execute this program, a file called “[Link]” will be generated in the
same directory as your Java program. The written data will be present in the file.

CHECK YOUR PROGRESS


9. The ______ method of FileWriter is used to release any system resources
associated with the writer.
10. FileWriter is used for ____________ to a file or a character-output stream.
11. When using FileReader, the default __________ of the system is used.

6.6
Buffered Streams: Reader and Writer

Reading data from a file


STUDY NOTE
BufferedReader is a Java class that offers
efficient reading of text from a character input The buffer size for
stream by implementing buffering mechanisms. BufferedInputStream
It is commonly used in the [Link] package and
to read data from files, input streams, or other BufferedOutputStream,
character sources. by default, is set to 8192
bytes (8 KB).
BufferedReader enhances reading efficiency
by reducing the frequency of I/O operations. It
achieves this by buffering larger chunks of data from the input stream, allowing for
more efficient reading. To create a BufferedReader, you wrap an existing Reader
object (such as FileReader or InputStreamReader) by passing it as a parameter
to the BufferedReader constructor.

import [Link].*;
public class FileReadExample {
public static void main(String[] args) {
08
try {
// Create a FileReader object to read from a file
NOTES
FileReader reader = new FileReader(“[Link]”);

BufferedReader bufferedReader = new Buffered
Reader(reader);
String line;
// Read data from the file and display it
while ((line = [Link]()) != null) {
[Link](line);
}
// Close the FileReader and BufferedReader
[Link]();
} catch (IOException e) {

[Link](“An error occurred: “ + e.
getMessage());
}
}
}

In this example, we create a FileReader object to read from a file named “input.
txt”. We wrap it with a BufferedReader for efficient reading of data.

We use a while loop to read each line of data from the file using the readLine()
method of the BufferedReader. The loop continues until readLine() returns
null, indicating the end of the file. Inside the loop, we print each line of data using
[Link](). Finally, we close the FileReader and BufferedReader
to release system resources.

Writing data to a file


BufferedWriter class provides efficient writing of character data to an output
stream by implementing buffering. It is part of the [Link] package and is
commonly used for writing data to files or other character-based destinations.

By buffering the characters, the Java BufferedWriter writes character data to an


output stream more effectively. To create a BufferedWriter, you need to wrap
an existing Writer object, such as FileWriter or OutputStreamWriter, by
passing it as a parameter to the BufferedWriter constructor.

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

try (BufferedWriter writer = new BufferedWriter
(new FileWriter(“[Link]”))) {
[Link](“Hello, World!”);
[Link]();
[Link](“This is a sample text.”);
} catch (IOException e) {

[Link](“An error occurred: “ + e.
09
NOTES }
getMessage());

}
}
We import the necessary classes, including BufferedWriter and FileWriter,
from the [Link] package. Inside the main() method, we create a
BufferedWriter object by wrapping a FileWriter object. Characters are written
by the FileWriter to the output file (“[Link]”).
We use the write() method of BufferedWriter to write the text “Hello, World!”
to the file. The newLine() method is called to insert a line break. Then, we write
another line of text using the write() method. Any IOException that may occur
during file writing is caught and handled in the catch block, where an error message
is displayed.

CHECK YOUR PROGRESS


12. The readLine() method of BufferedReader reads a line of text from the input
stream and returns it as an integer [True/False]
13. The close() method of BufferedWriter is not necessary as it is automatically
closed when the program ends [True/False]
14. IOException is a checked exception that can be thrown by BufferedWriter
methods[True/False]
15. Alice is working on a program where she needs to read data from a text
file, perform some modifications, and then write the modified data back to
another file. Which classes in Java can Alice use to accomplish this task?

6.7
Serialization
In Java, the process of turning an object into
a stream of bytes that can be quickly stored STUDY NOTE
in a file or sent over the internet is known as Serialization in Java not
serialization. It allows objects to be saved and only allows objects to be
reconstructed later, preserving their state and stored or transmitted, but
structure. it also enables complex
data structures to be
Serialization is primarily used for object
serialized. This means that
persistence, communication, and sharing of
entire object graphs can be
objects between different Java applications.
serialized, including objects
To make an object serializable, the Serializable
that have references to
interface is implemented by class. This interface
other objects.
acts as a marker, indicating that the object can
10 be serialized.
The values of an object’s member variables are included in the sequence of bytes
that represent the object’s state during serialization. Non-serializable member
NOTES
variables, such as transient variables, are not serialized.

The ObjectOutputStream class provides the ability to write objects to an output


stream. It takes care of converting the object into a serialized form and writing it to
a file or other output destination. The ObjectInputStream uses to read serialized
objects from an input stream(deserialization). It reconstructs the objects by reading
the byte stream and converting it back into objects.

Serialization

OBJECT STEAM

Deserialization

Fig 1: Serialization and Deserialization

import [Link].*;
class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
public void display() {
[Link](“Name: “ + name + “, Age: “ + age);
}
}
public class SerializationExample {
public static void main(String[] args) {
// Serialization
Person person = new Person(“John Doe”, 30);
String filename = “[Link]”;

try (FileOutputStream fileOutputStream = new FileOutput
Stream(filename);

ObjectOutputStream objectOutputStream = new
ObjectOutputStream(fileOutputStream)) {
[Link](person);

[Link](“Object serialized and saved to
“ + filename);
} catch (IOException e) {
11
NOTES 
[Link](“An error occurred during
serialization: “ + [Link]());
}
// Deserialization
Person deserializedPerson = null;

try (FileInputStream fileInputStream = new FileInput
Stream(filename);

ObjectInputStream objectInputStream = new Object
InputStream(fileInputStream)) {

deserializedPerson = (Person) objectInputStream.
readObject();

[Link](“Object deserialized from “ +
filename);
} catch (IOException | ClassNotFoundException e) {

[Link](“An error occurred during
deserialization: “ + [Link]());
}
// Display the deserialized object
if (deserializedPerson != null) {
[Link]();
}
}
}

The Person class implements the Serializable interface, indicating that objects
of this class can be serialized. In the SerializationExample class, a Person
object is created with some data. The Person object is serialized by writing it to an
ObjectOutputStream, which is wrapped around a FileOutputStream to write
to a file. The serialized object is saved to a file named “[Link]”.

During deserialization, the object is read from the file using an ObjectInputStream,
which is wrapped around a FileInputStream. The deserialized object is then cast
to a Person object and assigned to deserializedPerson.

Finally, the deserialized object is displayed by invoking the display() method.

CHECK YOUR PROGRESS


16. The Serializable interface in Java is a functional interface that contains a
single method for serialization [True/False]
17. Serializing an object also serializes its object references, preserving the
entire object graph [True/False]
18. ______ can only be performed on objects that have been previously serialized.
19. The order of ______ object fields during deserialization must match the order
in which they were written during serialization.

12
Activity
NOTES
You have a Java application that performs serialization and deserialization of
objects. The application uses a custom class called Employee that implements
the Serializable interface. The Employee class has several attributes such as
name, age, and salary. Suppose you have serialized an Employee object named
employeeObj and saved it to a file called “[Link]”. Now, you want to
deserialize the object and retrieve its data. Write Java code to perform the
deserialization process and display the name, age, and salary of the deserialized
Employee object.

6.8
Summary

● Streams are a fundamental aspect of handling input and output operations in


Java, enabling sequential data reading and writing.
● While the OutputStream class manages transmitting data to a destination, the
InputStream class makes it easier to read data from a source.
● For dealing with character data in text files, the FileReader and FileWriter
classes prove useful. The former is employed for reading, whereas the latter
for writing.
● BufferedReader and BufferedWriter classes offer buffering capabilities,
optimizing the efficiency of reading and writing operations involving text data.
● The BufferedReader class focuses on reading text from a character-input
stream, while the BufferedWriter class excels at writing text to a character-
output stream.
● Serialization encompasses the conversion of an object into a byte sequence,
suitable for storage or transmission.
● Deserialization, conversely, involves reconstructing an object from its serialized
form. In Java, the Serializable interface is implemented by classes to indicate
their serializability.
● The ObjectInputStream and ObjectOutputStream classes are utilized for
handling serialization and deserialization processes.
● Java facilitates console input through the [Link]() method. This
method allows for user interaction and the retrieval of data entered through
the console.

13
NOTES 6.9
Case Study

Flipkart’s File Handling System using Java I/O


Flipkart, one of India’s leading e-commerce companies, extensively utilizes Java
I/O for its file handling system. Java I/O plays a crucial role in various aspects of
Flipkart’s operations, including inventory management, order processing, and data
analytics.

1. Inventory Management:
● Flipkart uses Java I/O to read and process large CSV files containing
inventory data from suppliers.
● The company leverages BufferedReader and FileInputStream to efficiently
read the CSV files and parse the data.
● The data extracted from these files is then processed and stored in Flipkart’s
inventory management system.
2. Order Processing:
● When customers place orders on Flipkart’s platform, Java I/O is utilized for
various order-related tasks.
● FileWriter and BufferedWriter are employed to write order data to files,
which includes order details, customer information, and shipping addresses.
● These files are then processed by backend systems to facilitate order
fulfillment, inventory updates, and generating shipping labels.
3. Data Analytics:
● Flipkart collects a massive amount of data related to customer behavior,
sales, and product analytics.
● For effective data processing and analysis, Java I/O is essential for reading
and writing data to and from files.
● The company utilizes various Java I/O classes such as DataInputStream,
DataOutputStream, ObjectInputStream, and ObjectOutputStream to
handle structured data and store it in appropriate formats.
4. Log Management:
● Flipkart relies on logging to monitor system activities, track errors, and
ensure smooth operations.
● Java’s logging framework, which uses Java I/O, is integrated into Flipkart’s
systems to generate log files.
● The log files are created and managed using FileHandler and BufferedWriter,
allowing Flipkart’s development and operations teams to analyze system
behavior and troubleshoot issues effectively.

14
Benefits:
NOTES
● Scalability: Java I/O provides a scalable solution for Flipkart’s file handling
needs, allowing efficient processing of large volumes of data.
● Performance: Utilizing Java I/O’s buffered streams helps optimize read and
write operations, improving overall system performance.
● Flexibility: Java I/O’s diverse set of classes and functionalities enable Flipkart
to handle different file formats and data structures efficiently.
● Reliability: Flipkart’s extensive use of Java I/O ensures reliable and consistent
file handling, contributing to a seamless customer experience.

Flipkart’s adoption of Java I/O in its file handling system showcases the versatility
and effectiveness of Java’s input/output capabilities, enabling efficient data
processing, order management, and analytics in the context of a large-scale
e-commerce platform.

Questions:
1. How does Flipkart leverage Java I/O in its inventory management system?
Explain the role of Java I/O classes and techniques in processing and storing
inventory data obtained from suppliers’ CSV files.
2. Discuss the importance of efficient file handling using Java I/O in Flipkart’s order
processing system. Explain how FileWriter, BufferedWriter, and other Java I/O
classes are utilized to write order data to files, and how this contributes to the
smooth functioning of order fulfillment and inventory management processes.
3. Analyze the significance of Java I/O in Flipkart’s data analytics infrastructure.
Describe the role of Java I/O classes such as DataInputStream,
DataOutputStream, ObjectInputStream, and ObjectOutputStream in handling
structured data, storing it in appropriate formats, and facilitating effective data
analysis and reporting.

6.10
Terminal Questions

SHORT ANSWER QUESTIONS


1. You are developing a text-based quiz application in Java where users can
participate in multiple-choice quizzes. The application allows users to enter their
answers through the console. In the context of the text-based quiz application,
explain how you would utilize the console to read user inputs, validate the
answers, and provide appropriate feedback to the users based on their
responses.

15
NOTES 2. Emily is developing a chat application where she needs to continuously read
messages from a file and display them on the screen. At the same time, she
wants to allow users to enter new messages from the console and write
them to the same file. Which classes in Java can Emily use to implement this
functionality?
3. Develop a program that serializes a collection of objects to a file. Create a class
called “Product” with attributes such as id, name, and price. Create a collection
of Product objects and serialize it to a file. Then, deserialize the file to retrieve
the collection of objects.

LONG ANSWER QUESTIONS


1. You are developing a file transfer application in Java that allows users to send
and receive files over a network. The application utilizes InputStream and
OutputStream to handle the data transfer between the sender and receiver.
Consider the scenario where a user wants to send a large file to another user
using the file transfer application. Describe how you would use InputStream
and OutputStream to accomplish this task efficiently, taking into consideration
factors such as buffering, data segmentation, and ensuring reliable transmission.
2. Create a Java program that uses BufferedReader to read a text file and counts
the number of times a given word appears in the file. Use a buffered approach
to improve performance.

MULTIPLE CHOICE QUESTIONS


1. Which of the following statements is true regarding the InputStream and
OutputStream classes in Java?
a) InputStream is used for writing data to a destination, while OutputStream
is used for reading data from a source.
b) InputStream is an abstract class for byte-oriented input streams, while
OutputStream is an abstract class for byte-oriented output streams.
c) InputStream and OutputStream are concrete classes that provide direct
implementations for reading and writing data.
d) 
InputStream and OutputStream are interchangeable and can be used
interchangeably for reading and writing data.
2. John is developing a file compression program in Java. He wants to write the
compressed data to a new file. Which class in Java can John use to achieve
this?
a) FileInputStream b) DataOutputStream
c) ObjectInputStream d) FileOutputStream
3. Sarah is working on a multimedia application that needs to read audio data from
a network stream. Which class in Java can Sarah use to achieve this?
a) OutputStream
b) ByteArrayInputStream
c) ObjectInputStream
d) InputStream
16
4. David is creating a command-line program that needs input from the console
from users. He wants to read integer values entered by the user. Which class
NOTES
in Java can David use to achieve this?
a) BufferedReader b) Scanner
c) InputStreamReader d) System
5. John is developing a command-line application that requires users to enter their
personal information. He wants to read the user’s input from the console and
store it for further processing. John decides to use the console to read the data
because it provides a convenient way for users to interact with the application.
How can John read user input from the console in Java?
a) By using the [Link] stream and InputStreamReader.
b) By using the Scanner class.
c) By using the BufferedReader class.
d) All of the above.
6. Emma is developing a simple banking application where users can perform basic
banking operations such as checking their balance and making transactions.
The application needs to read user input to process these operations. Emma
decides to use the Scanner class to read input from the console. How can
Emma use the Scanner class to read user input from the console in Java?
a) By creating an instance of the Scanner class and using its methods like
nextInt() and nextLine().
b) By using the [Link] stream directly to read user input.
c) By using the BufferedReader class along with the Scanner class.
d) By using the InputStreamReader class along with the Scanner class.
7. What is the advantage of using buffered streams over non-buffered streams in
Java?
a) Buffered streams provide encryption for secure data transfer.
b) Buffered streams have higher capacity to handle larger amounts of data.
c) Buffered streams are faster in reading and writing operations.
d) Buffered streams eliminate the need for error handling in I/O operations.
8. Which of the following methods is used to read a line of text from a
BufferedReader in Java?
a) read() b) readLine()
c) write() d) append()
9. What is the output of the following code snippet?
try (FileWriter writer = new FileWriter(“[Link]”)) {
[Link](“Hello”);
[Link](“World”);
}
a) The file “[Link]” will contain the text “HelloWorld” without any spaces.
b) The file “[Link]” will contain the text “Hello\nWorld” with a newline
character between the words.
17
NOTES c) The code will throw a FileNotFoundException.
d) The code will throw a IOException.
10. What is the output of the following code snippet?
try (BufferedReader reader = new BufferedReader(new
FileReader(“[Link]”))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
}
a) It will throw an IOException if an error occurs while reading the file.
b) It will print the total number of lines in the “[Link]” file.
c) It will throw a FileNotFoundException if the “[Link]” file does not exist.
d) It will print the contents of the “[Link]” file line by line.
11. What is the output of the following code snippet?
try (BufferedWriter writer = new BufferedWriter(new File-
Writer(“[Link]”))) {
[Link](“Hello”);
[Link]();
[Link](“World”);
}
a) The file “[Link]” will contain the text “Hello\nWorld” with a newline
character between the words.
b) The file “[Link]” will contain the text “HelloWorld” without any spaces
or newlines.
c) The code will throw a FileNotFoundException if the “[Link]” file does
not exist.
d) The code will throw an IOException if an error occurs while writing to the
file.
12. What is the output of the following code snippet?
try (FileReader reader = new FileReader(“[Link]”)) {
int data;
while ((data = [Link]()) != -1) {
[Link]((char) data);
}
}
a) It reads the contents of the “[Link]” file and prints each character on a
new line.
b) It reads the contents of the “[Link]” file and prints them as a single
continuous string.
c) It throws a FileNotFoundException if the “[Link]” file does not exist.
d) It throws an IOException if an error occurs while reading the file.

18
13. Which of the following is a valid reason for using serialization in Java?
NOTES
a) To encrypt and secure sensitive data during communication.
b) To improve the performance of an application.
c) To convert objects into a readable text format.
d) To store objects in a database.
14. Which of the following is a potential issue when deserializing objects in Java?
a) The serialized object loses all its methods.
b) Deserialization can result in a ClassNotFoundException.
c) Deserialized objects cannot be modified after deserialization.
d) Deserialization can only be performed on primitive data types.
15. Which of the following statements about serialization in Java is true?
a) Serialization is the process of converting an object into JSON format.
b) Serialized objects can only be saved to a text file.
c) All objects in Java are serializable by default.
d) 
The Serializable interface must be implemented by a class to make it
serializable.

6.11
Terminal Questions

CHECK YOUR PROGRESS


1. False 11. Character encoding
2. True 12. False
3. True 13. False
4. To be solved by student 14. True
5. False 15. To be solved by students
6. True 16. False
7. To be solved by student 17. True
8. readLine() 18. Deserialization
9. close() 19. Reading
10. Writing characters

SHORT ANSWER QUESTIONS


1. In the text-based quiz application, the console can be utilized to read user
inputs, validate answers, and provide feedback to the users based on their
responses. Here’s how it can be done:

19
NOTES ● Display the question: The application displays the quiz question along with
the available answer choices on the console.
● Read user input: The application prompts the user to enter their answer
through the console. It waits for the user to input their response.
● Read and validate the answer: The application reads the user’s input from
the console using a BufferedReader or Scanner. It compares the user’s
answer with the correct answer to determine if it is valid.
● Provide feedback: Based on the user’s response, the application provides
appropriate feedback. If the answer is correct, it displays a positive message.
If the answer is incorrect, it provides the correct answer and offers an
explanation or additional information.
● Repeat the process: The application continues to display the next question,
read the user’s input, validate it, and provide feedback until all the quiz
questions have been answered.
2. Emily can use the following classes in Java to implement the desired
functionality:
● FileReader: Emily can read messages from the file using the FileReader
class. FileReader is designed for reading character data from a file in a
character-by-character manner.
● BufferedReader: To increase efficiency, Emily can wrap the FileReader with
a BufferedReader. Buffering capabilities offered by BufferedReader make it
possible to read characters, arrays, and lines from the underlying FileReader
quickly and effectively.
● FileWriter: Emily can add new messages to the same file by using the
FileWriter class. FileWriter is designed for writing character data to a file.
● BufferedWriter: Emily can wrap the FileWriter with a BufferedWriter to
improve efficiency. BufferedWriter provides buffering capabilities, allowing
for the efficient writing of characters, arrays, and strings to the underlying
FileWriter.
3. import [Link].*;
import [Link];
import [Link];
class Product implements Serializable {
private int id;
private String name;
private double price;
public Product(int id, String name, double price) {
[Link] = id;
[Link] = name;
[Link] = price;
}
@Override
public String toString() {

return “Product [id=” + id + “, name=” + name +
“, price=” + price + “]”;

20
}
}
NOTES
public class SerializationExample {
public static void main(String[] args) {
List<Product> products = new ArrayList<>();
[Link](new Product(1, “Product 1”, 10.99));
[Link](new Product(2, “Product 2”, 19.99));
[Link](new Product(3, “Product 3”, 5.99));
// Serialization
try {

FileOutputStream fileOut = new FileOutput
Stream(“[Link]”);

ObjectOutputStream out = new ObjectOutput
Stream(fileOut);
[Link](products);
[Link]();
[Link]();
[Link](“Serialized data has been
saved to [Link]”);
} catch (IOException e) {
[Link]();
}
// Deserialization
List<Product> deserializedProducts = null;
try {

FileInputStream fileIn = new FileInputStream
(“[Link]”);

ObjectInputStream in = new ObjectInputStream
(fileIn);

deserializedProducts = (List<Product>) in.
readObject();
[Link]();
[Link]();
} catch (IOException | ClassNotFoundException e)
{
[Link]();
}
if (deserializedProducts != null) {
[Link](“Deserialized Products:”);
for (Product product : deserializedProducts)
{
[Link](product);
}
}
}
}

21
NOTES LONG ANSWER QUESTIONS
1. To efficiently transfer a large file using InputStream and OutputStream in the
file transfer application, the following steps can be taken:
Sender-side:
● Open an InputStream to read the file to be transferred.
● Open an OutputStream to send the data over the network.
● Implement buffering by wrapping the InputStream and OutputStream with
BufferedInputStream and BufferedOutputStream, respectively.
● Divide the file into smaller segments or chunks to reduce memory
consumption and improve transmission efficiency.
● Read a chunk of data from the InputStream and write it to the OutputStream
in a loop until the entire file is transferred.
● Flush the OutputStream to ensure all the data is sent.
● Close the InputStream and OutputStream to release system resources.
Receiver-side:
● Open an InputStream to receive the data over the network.
● Open an OutputStream to write the received data to a file.
● Implement buffering by wrapping the InputStream and OutputStream with
BufferedInputStream and BufferedOutputStream, respectively.
● Read the data from the InputStream and write it to the OutputStream in a
loop until the complete file is received.
● Flush the OutputStream to ensure all the data is written to the file.
● Close the InputStream and OutputStream to release system resources.
2. import [Link];
import [Link];
import [Link];
public class WordCount {
public static void main(String[] args) {
String filePath = “path/to/your/text/[Link]”;
String searchWord = “specificWord”;
int wordCount = 0;
try (BufferedReader reader = new BufferedRead-
er(new FileReader(filePath))) {
String line;
while ((line = [Link]()) != null) {
String[] words = [Link](“\\s+”); //
Split line into individual words
for (String word : words) {
if ([Link](search-
Word)) {
wordCount++;
}
}
}
22
} catch (IOException e) {
[Link]();
NOTES
}

[Link](“The word ‘” + searchWord + “’


occurs “ + wordCount + “ times in the file.”);
}
}

MCQS ANSWERS
1. b) InputStream is an abstract class for byte-oriented input streams, while
OutputStream is an abstract class for byte-oriented output streams.
2. d) FileOutputStream
3. d) InputStream
4. b) Scanner
5. d) All of the above.
6. a) By creating an instance of the Scanner class and using its methods like
nextInt() and nextLine().
7. c) Buffered streams are faster in reading and writing operations.
8. b) readLine()
9. a) The file “[Link]” will contain the text “HelloWorld” without any spaces.
10. d) It will print the contents of the “[Link]” file line by line.
11. a) The file “[Link]” will contain the text “Hello\nWorld” with a newline
character between the words.
12. b) It reads the contents of the “[Link]” file and prints them as a single
continuous string.
13. d) To store objects in a database.
14. b) Deserialization can result in a ClassNotFoundException.
15. d) 
The Serializable interface must be implemented by a class to make it
serializable

6.12
Assignment

MULTIPLE CHOICE QUESTIONS


1. What is the output of the following code snippet?
Console console = [Link]();
String input = [Link]();
[Link](“You entered: “ + input);
23
NOTES a) It prompts the user to enter a value, reads the input from the console, and
then prints “You entered: “ followed by the entered value.
b) It throws a NullPointerException because the [Link]() method
returns null.
c) 
It throws a NoSuchElementException because the [Link]()
method is not supported.
d) It prints “You entered: null” as the value of input.
2. What is the output of the following code snippet?
Scanner scanner = new Scanner([Link]);
[Link](“Enter your name: “);
String name = [Link]();
[Link](“Hello, “ + name + “!”);
a) It throws a NoSuchElementException because there is no input provided.
b) It prompts the user to enter their name, reads the input from the console,
and then prints “Hello, “ followed by the entered name.
c) It throws a NullPointerException because the [Link] object is null.
d) It prints “Hello, null!” as the value of name.
3. What is the output of the following code snippet?
import [Link].*;
class Person implements Serializable {
String name;
int age;
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
}
public class SerializationExample {
public static void main(String[] args) {
try (ObjectOutputStream outputStream = new Ob-
jectOutputStream(new FileOutputStream(“[Link]”))) {
Person person = new Person(“John”, 30);
[Link](person);
[Link](“Serialization com-
plete!”);
} catch (IOException e) {
[Link]();
}
}
}
a) It throws a ClassNotFoundException.
b) It throws a FileNotFoundException.
c) 
It prints “Serialization complete!” and creates a serialized file named
“[Link]”.
d) It throws a NotSerializableException.
24
4. What will be the output of the following code?
InputStream inputStream = new FileInputStream(“data.
NOTES
txt”);
int data = [Link]();
[Link](data);
a) The content of the “[Link]” file.
b) The number of bytes read from the file.
c) The ASCII value of the first character in the file.
d) An error will occur since the file is not closed after reading.
5. What will be the output of the following code?
OutputStream outputStream = new FileOutputStream(“output.
txt”);
String message = “Hello, World!”;
[Link]([Link]());
[Link]();
[Link](“Data written successfully.”);
a) “Hello, World!”
b) “Data written successfully.”
c) An error will occur since the file “[Link]” does not exist.
d) An error will occur because the output stream is not flushed before closing.

QUESTIONS
1. Develop a program that prompts the user to enter multiple lines of text and
writes them to a file using FileWriter. Ensure that each line is written on a new
line in the file.
2. Develop a program that copies the contents of one file to another file using
BufferedInputStream and BufferedOutputStream. Compare the execution time
of the buffered approach with the non-buffered approach.
3. Sarah is developing a quiz application where users can take multiple-choice
quizzes. The application needs to read the quiz questions and options from a
file and display them to the user. At the same time, the application should allow
users to select their answers by entering the option number from the console.
Sarah decides to use the console for reading user input and displaying the quiz
questions. How can Sarah read the quiz questions and options from a file and
display them to the user using the console in Java?
4. Implement a program that logs user activities to a file. Each time a user performs
an action, record the timestamp and the action description. Use FileWriter to
append the log entries to the file.
5. Write a Java program that demonstrates serialization and deserialization of an
object. Create a class called “Person” with attributes such as name, age, and
address. Serialize an object of the Person class to a file and then deserialize it
to recreate the object.

25
NOTES 6.13
References

Books:
● [Link]
hl=en&gbpv=1&dq=java+i/o&printsec=frontcover
● [Link]
AQBAJ?hl=en&gbpv=1&dq=java+i/o&printsec=frontcover

Web References:
● [Link]
● [Link]
● [Link]

26

You might also like