0% found this document useful (0 votes)
16 views

Unit-6 Notes

Uploaded by

omkartandale17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Unit-6 Notes

Uploaded by

omkartandale17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Unit VI File Handling and Design Patterns

File Handling: Introduction, Concepts of Stream, Stream Classes, Byte Stream Classes,
Character Stream, Classes, Using Stream, and Other Useful I/O Classes, Using the File Class,
Input/output Exceptions, Creation of Files, Reading/Writing Character, Reading/Writing
Bytes, Handling Primitive Data Types, Concatenating and Buffering Files, Random Access
Files.
Design Patterns: Introduction, Types of Design Patterns, Adapter, Singleton, Iterator

Java provides the java.io and java.nio packages for file handling, offering extensive
support for reading, writing, and managing files.

1. Introduction to File Handling

File handling in Java allows a program to interact with the system’s file storage, enabling
read and write operations on files and directories. Java abstracts file operations through a
series of classes and interfaces that make it easy to manipulate files and data streams.

Why File Handling?

 Persistence: Allows saving data beyond the program’s runtime.


 Data Transfer: Enables storing and retrieving data for further processing or sharing.
 Flexibility: Java provides multiple classes for handling different file types and data.

2. Concept of Streams

A stream is a sequence of data. In Java, streams are classified into:

 Byte Streams: Deal with raw binary data (e.g., images, videos).
 Character Streams: Deal with character data (e.g., text files).

2.1 Byte Stream

Byte streams work with raw binary data, reading and writing bytes directly. These streams
extend InputStream and OutputStream.

2.2 Character Stream

Character streams work with Unicode data, supporting internationalized text input and
output. These streams extend Reader and Writer.

Diagram: A diagram showing the hierarchy of streams in Java with InputStream,


OutputStream, Reader, and Writer as the base classes.
3. Stream Classes

Java provides various stream classes under java.io to handle input and output operations for
files and data.

3.1 Byte Stream Classes

 FileInputStream: Reads bytes from a file.


 FileOutputStream: Writes bytes to a file.
 BufferedInputStream: Buffers input to reduce I/O operations.
 BufferedOutputStream: Buffers output, enhancing performance.

3.2 Character Stream Classes

 FileReader: Reads characters from a file.


 FileWriter: Writes characters to a file.
 BufferedReader: Buffers character input, improving performance.
 BufferedWriter: Buffers character output.

Diagram: A chart showing the relationships among the byte and character stream classes in
Java’s java.io package.

4. Using Streams in Java

Streams make reading and writing data efficient by abstracting data flow, whether it's from
files, memory, or other sources.

Example Code (Using FileInputStream and FileOutputStream for byte data):

java
Copy code
FileInputStream fileInput = new FileInputStream("input.txt");
FileOutputStream fileOutput = new FileOutputStream("output.txt");

int byteData;
while ((byteData = fileInput.read()) != -1) {
fileOutput.write(byteData);
}
fileInput.close();
fileOutput.close();

In this code, we read bytes from an input file and write them to an output file. The loop
continues until the end of the file (-1).
5. Using the File Class

The File class in java.io represents files and directory pathnames, providing methods to
create, delete, and manage files.

Example Code:

java
Copy code
File file = new File("test.txt");
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}

Diagram: Illustrates the File class hierarchy and its common methods, showing its utility in
handling file operations.

6. Input/Output Exceptions in Java

I/O operations are prone to various exceptions, which need handling to prevent crashes or
data corruption.

Common I/O Exceptions

 FileNotFoundException: Raised when a file is not found.


 IOException: A general-purpose exception for input-output errors.
 EOFException: Signifies the end of file input.

Example Code:

java
Copy code
try {
FileInputStream fileInput = new FileInputStream("test.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("An I/O error occurred: " + e.getMessage());
}

7. Creating, Reading, and Writing Files

Creating Files

Java provides straightforward methods to create files with the File class, ensuring
persistence.

java
Copy code
File file = new File("newFile.txt");
if (file.createNewFile()) {
System.out.println("File created successfully.");
}

Reading and Writing Characters

Java’s character streams like FileReader and FileWriter make reading and writing text
files simple and efficient.

Example Code:

java
Copy code
FileReader reader = new FileReader("input.txt");
FileWriter writer = new FileWriter("output.txt");

int data;
while ((data = reader.read()) != -1) {
writer.write(data);
}
reader.close();
writer.close();

Reading and Writing Bytes

When handling binary files, byte streams are more efficient.

Example Code:

java
Copy code
FileInputStream inputStream = new FileInputStream("input.dat");
FileOutputStream outputStream = new FileOutputStream("output.dat");

int byteData;
while ((byteData = inputStream.read()) != -1) {
outputStream.write(byteData);
}
inputStream.close();
outputStream.close();

8. Handling Primitive Data Types

Java’s DataInputStream and DataOutputStream classes provide methods for reading and
writing primitive data types like int, double, and boolean.

Example Code:

java
Copy code
DataOutputStream dataOutput = new DataOutputStream(new
FileOutputStream("datafile.dat"));
dataOutput.writeInt(123);
dataOutput.writeDouble(3.14);
dataOutput.close();

9. Concatenating and Buffering Files

Buffered Files:

Buffered streams reduce the number of I/O operations, boosting performance.

java
Copy code
BufferedReader bufferedReader = new BufferedReader(new
FileReader("input.txt"));
BufferedWriter bufferedWriter = new BufferedWriter(new
FileWriter("output.txt"));

Concatenating Files:

Concatenation involves combining multiple files into one by sequentially reading from
multiple sources and writing them to a single destination.

10. Random Access Files

RandomAccessFile allows you to read and write data at any position in a file. This class is
especially useful for non-linear data access.

Example Code:

java
Copy code
RandomAccessFile randomFile = new RandomAccessFile("file.dat", "rw");
randomFile.seek(10); // Move to the 10th byte
int data = randomFile.read();
randomFile.close();

Design Patterns in Java


Design patterns are reusable solutions to recurring software design problems, enabling
developers to create well-structured, maintainable code.

1. Introduction to Design Patterns

Design patterns streamline software development by providing standard solutions to common


problems. They improve the efficiency of code structure, enabling scalability and reusability.

2. Types of Design Patterns


Creational Patterns

Focus on object creation. Examples include:

 Singleton: Ensures a class has only one instance.


 Factory Method: Provides a way to instantiate objects through subclasses.

Structural Patterns

Concerned with the structure and composition of classes. Examples:

 Adapter: Allows incompatible interfaces to work together.


 Decorator: Adds responsibilities to objects dynamically.

Behavioral Patterns

Address object communication. Examples:

 Iterator: Provides sequential access to collection elements.


 Observer: Defines a one-to-many dependency, notifying observers on changes.

3. Singleton Pattern

Ensures only one instance of a class is created and provides a global access point.

Code Example:

java
Copy code
public class Singleton {
private static Singleton instance;

private Singleton() {} // Private constructor

public static Singleton getInstance() {


if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

Diagram: Class diagram showing a Singleton with a private constructor and static
getInstance method.

4. Adapter Pattern
The Adapter pattern allows incompatible interfaces to interact by creating an adapter class
that acts as a bridge.

Code Example:

java
Copy code
interface Target {
void request();
}

class Adaptee {
void specificRequest() {
System.out.println("Specific request");
}
}

class Adapter implements Target {


private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
public void request() {
adaptee.specificRequest();
}
}

Diagram: UML diagram showing Target, Adaptee, and Adapter classes, illustrating the
Adapter pattern.

5. Iterator Pattern

The Iterator pattern provides sequential access to a collection without exposing its underlying
structure.

Code Example:

java
Copy code
List<String> list = new ArrayList<>();
list.add("Item1");
list.add("Item2");

Iterator<String> iterator = list.iterator();


while (iterator.hasNext()) {
System.out.println(iterator.next());
}

Diagram: Class diagram showing a Collection interface with an Iterator to illustrate the
Iterator pattern.
Summary of Key Design Patterns

Pattern Type Purpose


Singleton Creational Ensures a class has only one instance
Adapter Structural Allows incompatible interfaces to work together
Iterator Behavioral Provides sequential access to elements

You might also like