0% found this document useful (0 votes)
18 views68 pages

Unit 06

The document covers file handling and design patterns in Java, detailing concepts such as streams, byte and character streams, and file operations including reading and writing files. It also introduces design patterns, categorizing them into creational, structural, and behavioral types, and emphasizes their role in creating flexible and maintainable code. A case study on a Student Management System illustrates the practical application of these concepts.

Uploaded by

dongareom77
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)
18 views68 pages

Unit 06

The document covers file handling and design patterns in Java, detailing concepts such as streams, byte and character streams, and file operations including reading and writing files. It also introduces design patterns, categorizing them into creational, structural, and behavioral types, and emphasizes their role in creating flexible and maintainable code. A case study on a Student Management System illustrates the practical application of these concepts.

Uploaded by

dongareom77
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
You are on page 1/ 68

UNIT-06

File Handling and Design Patterns



Sachin D. Shelke
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

Case Study: Student Management System


Concept of Streams

Java programs perform I/O through streams.

A stream is an abstraction that either produces or consumes information.

A stream is a sequence of objects that supports various methods which can be pipelined to
produce the desired result.

Java implements streams within class hierarchies defined in the java.io package.

Java defines two types of streams: byte and character.

Byte streams provide a convenient means for handling input and output of bytes. Byte streams
are used, for example, when reading or writing binary data.

Character streams provide a convenient means for handling input and output of characters.
ByteStream

Byte streams are defined by using two class hierarchies.

At the top are two abstract classes: InputStream and OutputStream.

Each of these abstract classes has several concrete subclasses that handle the differences
between various devices, such as disk files, network connections, and even memory
buffers.

The abstract classes InputStream and OutputStream define several key methods that the
other stream classes implement.

Two of the most important are read( ) and write( ), which, respectively, read and write
bytes of data.
ByteStream
Character Stream


Character streams are defined by using two class hierarchies.

At the top are two abstract classes, Reader and Writer.

The abstract classes Reader and Writer define several key methods that the other stream

classes implement.

Two of the most important methods are read( ) and write( ), which read and write
characters of data, respectively.

These methods are overridden by derived stream classes.
Character Stream
Character Stream
Predefined Streams


all Java programs automatically import the java.lang package.

This package defines a class called System, which encapsulates several aspects of the run-time
environment.

System also contains three predefined stream variables: in, out, and err.

System.out refers to the standard output stream. By default, this is the console.

System.in refers to standard input, which is the keyboard by default.

System.err refers to the standard

error stream, which also is the console by default.
Reading Console Input


BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

Reading Characters

To read a character from a BufferedReader, use read( ). The version of read( ) that
we will be using is

int read( ) throws IOException

Each time that read( ) is called, it reads a character from the input stream and returns it as

an integer value
Reading Characters........Example
class BRDemo {
public static void main (String[] args) throws IOException{
char c;

BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter 'q' to quit: ");

do{
c=(char)bf.read();
System.out.print(" "+c);
}while(c!='q');

}
}
Reading Console Input


BufferedReader br = new BufferedReader(new InputStreamReader(System.in));


Reading Strings

To read a string from the keyboard, use the version of readLine( ) that is a member of the

BufferedReader class.

String readLine( ) throws IOException

it returns a String object.
Reading Strings........Example
import java.io.*;

class BRreadLine{
public static void main(String args[]) throws IOException{
String s;
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Lines of Text: ");
System.out.println("Enter 'stop' to quit: ");
System.out.println("--------------------------");

do{
s = bf.readLine();
System.out.println(s);
}while(!s.equals("stop"));

System.out.println("--------------------------");

}
}
Writing Console Output


Console output is most easily accomplished with print( ) and println( )

These methods are defined by the class PrintStream (which is the type of object referenced
by System.out)

PrintStream is an output stream derived from OutputStream, it also implements the low-level
method write( )

Thus, write( ) can be used to write to the console.

void write(int byteval)
Writing Console Output........Example
PrintWriter Class


PrintWriter is one of the character-based classes.

PrintWriter(OutputStream outputStream, boolean flushOnNewline)

Here, outputStream is an object of type OutputStream, and flushOnNewline controls whether

Java flushes the output stream every time a println( ) method is called. If flushOnNewline is

true, flushing automatically takes place. If false, flushing is not automatic.


PrintWriter Class
Reading and Writing Files


Two of the most often-used stream classes are FileInputStream and FileOutputStream,
which create byte streams linked to files.

To open a file, you simply create an object of one of these classes, specifying the name of the
file as an argument to the constructor.


FileInputStream(String fileName) throws FileNotFoundException


FileOutputStream(String fileName) throws FileNotFoundException
Reading and Writing Files


When you create an input stream, if the file does not exist, then FileNotFoundException is
thrown.


For output streams, if the file cannot be created, then FileNotFoundException is thrown.


When an output file is opened, any preexisting file by the same name is destroyed.


When you are done with a file, you should close it by calling close( ). It is defined by both
FileInputStream and FileOutputStream, as shown here:


void close( ) throws IOException
Reading and Writing Files


To read from a file, you can use a version of read( ) that is defined within FileInputStream. The one
that we will use is shown here:

int read( ) throws IOException


Each time that it is called, it reads a single byte from the file and returns the byte as an integer value.


To write to a file, you can use the write( ) method defined by FileOutputStream. Its simplest form is
shown here:

void write(int byteval) throws IOException

This method writes the byte specified by byteval to the file.
Reading and Writing Files....Example
public class Main { try{
fos=new FileOutputStream("abc.txt");
public static void main(String[] args) throws IOException{ }catch(FileNotFoundException e){
// write your code here System.out.println("Unable to create output file.....");
int i; return;
FileInputStream fis; }
FileOutputStream fos;
try{
do{
try{ i= fis.read();
fis=new FileInputStream("xyz.txt"); if(i!=-1)
}catch(FileNotFoundException e){ fos.write(i);
System.out.println("File Not found....."); }while(i!=-1);
return; }catch(IOException e){
} System.out.println("Some Error has been occurred while
copying the file....");
}

fis.close();
fos.close();
}
}
Java File Operations
Reading and Writing Files
Java ‘File’ Class Methods
Java File Information
package com.company;
import java.io.*;
public class Main {
public static void main(String[] args) {
// write your code here
File fileObj = null;
try {
fileObj = new File("TestFile.txt");
if (fileObj.createNewFile())
System.out.println("File Created : " + fileObj.getName());
else
System.out.println("File is already present : " + fileObj.getName());
} catch (IOException e) {
System.out.println("An Error Occured while creating file.....");
}
System.out.println("File Path: " + fileObj.getAbsolutePath());
System.out.println("File size in bytes: " + fileObj.length());
System.out.println("Readable: " + fileObj.canRead());
System.out.println("Writable: " + fileObj.canWrite());
}
}
Java FileReader/FileWriter Class
public class Main {
public static void main(String[] args) {
// write your code here
FileWriter fileWriter=null;
FileReader fileReader=null;
String str = "This is the string to be written in the file for reading...";
char[] carr =new char[100];

try{
fileWriter = new FileWriter("TestFile.txt");
fileWriter.write(str);
fileWriter.close();
}catch(IOException e){
System.out.println("An Error while handling file...");
}
try{
fileReader = new FileReader("TestFile.txt");
fileReader.read(carr);
String fileContent = new String(carr);
System.out.println("File Content: "+fileContent);
fileReader.close();
}catch(IOException e){
System.out.println("An Error while handling file...");
}
}
}
Java FileReader/FileWriter Class
import java.io.*;
public class Main {
public static void main(String[] args) {
// write your code here
FileWriter fileWriter=null;
FileReader fileReader=null;
String str ="This is the string to be written in the file for reading...\nThis the string to be printed on new line";
try{
fileWriter = new FileWriter("TestFile.txt");
fileWriter.write(str);
fileWriter.close();
}catch(IOException e){
System.out.println("An Error while handling file...");
}
try{
File f =new File("TestFile.txt");
fileReader = new FileReader(f);
char carr[]=new char[(int)f.length()];

fileReader.read(carr);
String fileContent = new String(carr);
System.out.println("File Content: "+fileContent);
fileReader.close();
}catch(IOException e){
System.out.println("An Error while handling file...");
}
}
}
Java File Input with Scanner Class
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args){
// write your code here
FileWriter fileWriter=null;
FileReader fileReader=null;
String str = "This is the string to be written in the file for reading...\nThis the string to be printed on new line";

try{
fileWriter = new FileWriter("TestFile.txt");
fileWriter.write(str);
fileWriter.close();
}catch(IOException e){
System.out.println("An Error while handling file...");
}
try{
File file =new File("TestFile.txt");
Scanner sc = new Scanner(file);
while(sc.hasNext()) {
String fcontent = sc.nextLine();
System.out.println("File Content: " + fcontent);
}
sc.close();
}catch(IOException e){
System.out.println("File Error.... " );
}
}
}
File Records
class Student{ void readFile(){
String sname; String string;
int srn; //String[] line;
double smarks; try{
File file = new File("TestFile.txt");
Scanner sc = new Scanner(file);
void getData(){ System.out.println("\n");
Scanner sc = new Scanner(System.in); while(sc.hasNext()){
System.out.println("\nEnter Student Details: "); string = sc.nextLine();
System.out.print("Student Name: "); String line[] = string.split(" ");
sname = sc.nextLine();
System.out.println("Roll Number: "+line[0]);
System.out.print("");
System.out.println("Name: "+line[1]);
System.out.print("Student Roll Number: ");
System.out.println("Marks: "+line[2]);
srn = sc.nextInt();
System.out.println();
System.out.print("");
}
System.out.print("Student Marks: ");
sc.close();
smarks = sc.nextDouble();
System.out.print(""); }catch(IOException e){
} System.out.print("File Writing Error.... ");
void writeFile(){ }
String string; int n; }
FileWriter fileWriter = null; }
try{
fileWriter = new FileWriter("TestFile.txt");
public class Main {
getData();
string= srn+" "+sname+" "+smarks+"\n";
fileWriter.write(string);
public static void main(String[] args) {
getData();
// write your code here
string= srn+" "+sname+" "+smarks+"\n";
Student s = new Student();
fileWriter.write(string);
s.writeFile();
fileWriter.close();
s.readFile();
}catch(IOException e){
}
System.out.print("File Writing Error.... ");
} }
}
Random Access File


RandomAccessFile is used for reading and writing to random access file.

A random access file behaves like a large array of bytes. There is a cursor
implied to the array called file pointer, by moving the cursor we do the read write
operations.

If end-of-file is reached before the desired number of byte has been read than
EOFException is thrown. It is a type of IOException.

RandomAccessFile class extends Object class and implements DataInput and
DataOutput interfaces with additional methods to support random access.
Therefore, it can be used for both reading and writing simultaneously.
Random Access File....Constructors
Random Access File....Methods
Random Access File....Example
public class Main { randomAccessFile.seek(2);
System.out.println(randomAccessFile.readInt()+" ");
public static void main(String[] args) throws
IOException{ randomAccessFile.seek(randomAccessFile.length());
randomAccessFile.writeBoolean(true);
// write your code here
RandomAccessFile randomAccessFile = new randomAccessFile.seek(4);
RandomAccessFile("TestFile.txt","rw"); System.out.println(randomAccessFile.readBoolean());
randomAccessFile.setLength(0); randomAccessFile.close();
randomAccessFile.writeChar('C');
RandomAccessFile raf = new
randomAccessFile.writeInt(12345); RandomAccessFile("Test.txt","rw");
randomAccessFile.writeDouble(1234.50); raf.setLength(0);
System.out.println("Current length of file is: "+ for(int i=0; i<10; i++){
randomAccessFile.length()); raf.writeInt(i);
}
randomAccessFile.seek(0); System.out.println("Current length of file is:
System.out.print(randomAccessFile.readChar()+" "+raf.length());
"); raf.seek(9*4);
System.out.print(randomAccessFile.readInt()+" "); System.out.println("Int Value: "+raf.readInt());
raf.close();
System.out.println(randomAccessFile.readDouble()+" }
"); }
Random Access File
Design Patterns

A design patterns are well proved solution for solving specific problem.


design patterns are programming language independent strategies for
solving the common object-oriented design problems. That means, a design
pattern represents an idea, not a particular implementation.


By using the design patterns you can make your code more flexible, reusable
and maintainable. It is the most important part because java internally follows
design patterns
Design Patterns.... When to Use

We must use the design patterns during the analysis and requirement phase
of SDLC(Software Development Life Cycle).


Categorization of design Patterns

 Core Java (or JSE) Design Patterns.

 JEE Design Patterns.


Design Patterns.... Core Java ( 3 types)

1. Creational Design Patterns:

2. Structural Design Patterns

3. Behavioral Design Patterns


Creational Design Patterns

1. Creational design patterns are concerned with the way of creating objects.

StudentRecord s1=new StudentRecord();

2. Hard-Coded code is not the good programming approach. Here, we are creating the
instance by using the new keyword. Sometimes, the nature of the object must be
changed according to the nature of the program. In such cases, we must get the help
of creational design patterns to provide more general and flexible approach.
Creational Design Patterns

1. Factory Pattern

2. Abstract Factory Pattern

3. Singleton Pattern

4. Prototype Pattern

5. Builder Pattern

6. Object Pool Pattern


Singleton Pattern

Singleton Pattern says that just "define a class that has only one instance and provides a
global point of access to it".

In other words, a class must ensure that only single instance should be created and single
object can be used by all other classes.

There are two forms of singleton design pattern

1. Early Instantiation: creation of instance at load time.

2. Lazy Instantiation: creation of instance when required.


Singleton Pattern

Advantage: Saves memory because object is not created at each request. Only single
instance is reused again and again.

Usage: Singleton pattern is mostly used in multi-threaded and database applications. It is


used in logging, caching, thread pools, configuration settings etc.
Singleton Pattern
Singleton Pattern

How to Create:


To create the singleton class, we need to have static member of class, private constructor and
static factory method


Static member: It gets memory only once because of static, itcontains the instance of the
Singleton class.


Private constructor: It will prevent to instantiate the Singleton class from outside the class.


Static factory method: This provides the global point of access to the Singleton object and
returns the instance to the caller.
Singleton Pattern
class A{
private static A obj= new A();
private A(){}

public static A getA(){


return obj;
}
}

public class Main {

public static void main(String[] args) {


// write your code here
System.out.println("Object not created yet...");
A a = A.getA();
System.out.println("Same object is used...");

}
}
Structural Design Patterns

Structural design patterns are concerned with how classes and objects can be
composed, to form larger structures.

The structural design patterns simplifies the structure by identifying the


relationships.

These patterns focus on, how the classes inherit from each other and how they
are composed from other classes.
Structural Design Patterns
1. Adapter Pattern

2. Bridge Pattern

3. Composite Pattern

4. Decorator Pattern

5. Facade Pattern

6. Flyweight Pattern

7. Proxy Pattern
Adapter Patterns

An Adapter Pattern says that just "converts the interface of a class into another interface
that a client wants".

In other words, to provide the interface according to client requirement while using the
services of a class with a different interface.

The Adapter Pattern is also known as Wrapper.

Advantages:

It allows two or more previously incompatible objects to interact.

It allows reusability of existing functionality.


Adapter Patterns

There are the following specifications for the adapter pattern:

Target Interface: This is the desired interface class which will be used by the clients.

Adapter class: This class is a wrapper class which implements the desired target
interface and modifies the specific request available from the Adaptee class.

Adaptee class: This is the class which is used by the Adapter class to reuse the existing
functionality and modify them for desired use.

Client: This class will interact with the Adapter class.


Adapter Patterns
Adapter Patterns
Adapter Patterns
Behavioral Design Patterns

Behavioral design patterns are concerned with the interaction and responsibility
of objects.

In these design patterns, the interaction between the objects should be in such a
way that they can easily talk to each other and still should be loosely coupled.

That means the implementation and the client should be loosely coupled in order
to avoid hard coding and dependencies.
Behavioral Design Patterns
1. Chain Of Responsibility Pattern

2. Command Pattern

3. Interpreter Pattern

4. Iterator Pattern

5. Mediator Pattern

6. Memento Pattern

7. Observer Pattern

8. State Pattern

9. Strategy Pattern

10. Template Pattern

11. Visitor Pattern

12. Null Object


Iterator Pattern
Iterator Pattern is used "to access the elements of an aggregate object
sequentially without exposing its underlying implementation".

The Iterator pattern is also known as Cursor.

It supports variations in the traversal of a collection.

It simplifies the interface to the collection.


Iterator Pattern
Iterator Pattern
Iterator Pattern
Factory Method Pattern


A Factory Pattern or Factory Method Pattern says that just define an interface or
abstract class for creating an object but let the subclasses decide which class to
instantiate.


In other words, subclasses are responsible to create the instance of the class.


The Factory Method Pattern is also known as Virtual Constructor.
Factory Method Pattern
Factory Method Pattern
Factory Method Pattern
Strategy Pattern


A Strategy Pattern says that "defines a family of functionality, encapsulate each
one, and make them interchangeable".


The Strategy Pattern is also known as Policy.


Usage:


When the multiple classes differ only in their behaviors.e.g. Servlet API.


It is used when you need different variations of an algorithm.
Strategy Pattern


A Strategy Pattern says that "defines a family of functionality, encapsulate each one, and
make them interchangeable".


The Strategy Pattern is also known as Policy.


Benefits:


It provides a substitute to subclassing.


It defines each behavior within its own class, eliminating the need for conditional
statements.


It makes it easier to extend and incorporate new behavior without changing the application.
Strategy Pattern
Strategy Pattern
Strategy Pattern
Case Study:

Student Management System


References

1. Java Complete Reference

2. https://www.javatpoint.com/adapter-pattern

You might also like