MCA Lab On Java Programming Unit 6 Java Input Output
MCA Lab On Java Programming Unit 6 Java Input Output
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.
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
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.
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.
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]();
}
}
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
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.
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());
}
}
}
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.
6.6
Buffered Streams: Reader and Writer
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.
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.
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.
Serialization
OBJECT STEAM
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.
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
13
NOTES 6.9
Case Study
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
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.
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
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
}
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
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