MCA Java Programming Unit 6 Java Input Output
MCA Java Programming Unit 6 Java Input Output
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.
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
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.
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.
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.
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:
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);
}
}
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.
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
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.
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:
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.
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:
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]();
}
}
}
13
NOTES 6.5
Character-oriented Classes
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.
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]();
}
}
}
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.
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.
6.6
Buffered Streams
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.
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.
Example:
Reading from a file using BufferedInputStream
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.
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]();
}
}
}
Example:
Reading from a file using BufferedReader
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.
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.
6.7
Serialization and Deserialization
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.
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
}
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.
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
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.
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
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?
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
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
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