Software Design and Analysis
CS-3004
Lecture#07
Dr. Javaria Imtiaz,
Mr. Basharat Hussain,
Mr. Majid Hussain
Agenda
• I/O programming
• Streams
• Byte stream
• Character stream
• Data stream
2
Java I/O
• Java I/O (Input and Output) is used to process the input and
produce the output.
• Java uses the concept of a stream to make I/O operation fast. The
java.io package contains all the classes required for input and
output operations.
3
Stream
• A stream is a sequence of data. In Java, a stream is composed of
bytes. It's called a stream because it is like a stream of water that
continues to flow.
4
Streams
• Streams represents a Source (which generates the data in the form of
Stream) and a destination (which consumes or read data available as
Stream).
• Streams supports a huge range of source and destinations including disk
file, arrays, other devices, other programs etc.
5
File Handling
• File handling is an important part of any application.
• File Handling implies how to read from and write to file in Java.
• Java provides the basic I/O package for reading and writing
streams.
• Java.io package allows to do all Input and Output tasks in Java.
• It provides several methods for creating, reading, updating, and
deleting files.
6
Java’s File Management
• Java class java.io.File defines platform-independent manipulation
of file system (Files & directories) by providing whether the file
– exists
– is read protected
– is write protected
– is, in fact, a directory
7
File Class
• The File class from the java.io package, allows us to work with
files.
• To use the File class, create an object of the class, and specify
the filename or directory name:
8
File Class
• A File object can refer to either a file or directory
File file1 = new File(“data.txt”);
File file2 = new File(“C:\Java”);
• To obtain the path to the current working directory use
System.getProperty(“user.dir”);
• To obtain the file or path separator use
System.getProperty (“file.separator”);
System.getProperty (“path.separator”);
9
Useful File Methods
10
Create a File
Import the File Class
Import the IOException class to handle errors
Create
Object of a
File
In try block, write a code that has to be executed and catch block will handle the errors occur in try
block. In this case, the most expected error is IOExpection and that will be handled by the catch
block.
11
Get File Information A path can be absolute or relative. An
absolute path contains the full path
from the root of the file system down to
the file or directory it points to. A
relative path contains the path to the
file or directory relative to some other
path.
Output
12
Directory Listing Example
import java.io.*;
public class DirListing {
public static void main(String[] args) {
File dir = new File(System.getProperty(“user.dir”));
if (dir.isDirectory())
{
System.out.println(“Directory of ” + dir);
String[] listing = dir.list();
for (int i=0; i < listing.length; i++) {
System.out.println(“\t” + listing[i]);
}
}
}
}
13
Directory Listing, Result
> java DirListing
Direcotry of c:\Java\
DirListing.class
DirListing.java
Test
TryCatchExample.class
TryCatchExample.java
XslTransformer.class
XslTransformer.java
14
Input/Output Streams
• Java IO package provides over 60 input/output classes
(streams)
• Streams are ordered sequence of data that have a source
(input), or a destination (output)
15
Streams
Java uses the concept of a stream to make I/O operations on a file.
These handle data in bytes (8
bits) i.e., the byte stream classes
read/write data of 8 bits. Using
these you can store characters,
videos, audios, images etc.
These handle data in 16 bit
Unicode. Using these you can
read and write text data only.
16
Basic IO Algorithm
• Reading • Writing
open a stream open a stream
while more information while more information
read information write information
close the stream close the stream
17
Byte Streams
• Read and write 8-bit
bytes
• InputStream and
OutputStream are
abstract super
classes
• Typically used to read
and write binary data
such as images and
sounds
18
Character Streams
• Read and write 16-bit
characters
• Reader and Writer
are the abstract classes
• Use readers and writers
to read and write textual
information
19
I/O Super Classes
InputStream
Reader
int read();
int read();
int read(byte buffer[]);
int read(char cbuf[]);
int read(byte buffer[],
int read(char cbuf[],
int offset,
int offset,
int length)
int length)
Writer OutputStream
int write(byte b);
int write(int c);
int write(byte buffer[]);
int write(char cbuf[]);
int write(byte buffer[],
int write(char cbuf[],
int offset,
int offset,
int length)
int length)
20
FileOutputStream Example
21
FileInputStream Example
22
Character File Streams
FileReader
• FileReader
in
FileWriter
• FileWriter
out
23
Write to a file
Java FileWriter class is used to
write data to a file.
write() method to
write some text into
the file
The close() method is used to
close the file output stream
and releases all system
resources associated with this
stream.
24
Read a File
FileReader is used for reading
streams of characters.
25
Buffer Streams
• Buffer data while reading or writing, thereby reducing the number of
accesses required on the original data source.
• More efficient than similar non-buffered streams and are often used
with other streams
• The buffer size may be specified, or default size may be accepted
BufferedReader BufferedInputStream
BufferedWriter BufferedOutputStream
Character Byte Streams
Streams
26
Using Buffer Streams
import java.io.*;
public class Copy {
public static void main(String[] args) throws IOException {
// opening the streams
FileReader in = new FileReader (“infile.txt");
BufferedReader br = new BufferedReader(in);
FileWriter out = new FileWriter ("outfile.txt");
BufferedWriter bw = new BufferedWriter(out);
// processing the streams
String aLine = null;
while ((aLine = br.readLine()) != null) {
bw.write(aLine, 0, aLine.length());
}
// closing the streams
in.close(); out.close();
}
}
27
Database Connectivity
Java Database Connectivity
JDBC stands for Java Database Connectivity.
JDBC is a Java API to connect and execute the query with the
database.
The JDBC API defines interfaces and classes for writing
databases applications in Java by making database
connection.
29
Database
• Database is a set of files containing application data.
• This data needs to be inserted, deleted, updated, extracted for any valid
reason.
– You can write programs to perform all such actions
– You can use readymade database management software like Oracle and MySQL.
• A Database Management Software or DBMS is used for storing, manipulating,
and managing data in a database environment. Users can construct their own
databases using a DBMS to satisfy their business requirements.
30
Overview
31
JDBC Architecture
32
Why Should We Use JDBC
• Before JDBC, ODBC API was the database API to connect
and execute the query with the database. But, ODBC API
uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its
own API (JDBC API) that uses JDBC drivers (written in Java
language).
• We can use JDBC API to handle database using Java
program and can perform the following activities:
– Connect to the database
– Execute queries and update statements to the database
– Retrieve the result received from the database.
33
JDBC Drivers
Java Application
• JDBC consists of two parts: JDBC API
– JDBC API, a purely Java-based API
JDBC Driver Manager
– JDBC Driver Manager, which
communicates with vendor-specific JDBC Driver API
drivers that perform the real JDBC-ODBC
Bridge
Vendor Specific
JDBC Driver
communication with the database.
Vendor Specific Database
ODBC Driver
Database
35
Basic steps to use a database in Java
1.Establish a connection
2.Create JDBC Statements
3.Execute SQL Statements
4.GET ResultSet
5.Close connections
36
Handing SQL
Exception
Setting DB
Credentials
CRUD Query
Load driver
Establish
Connection
Execute queries
with the database
37
JDBC imports
1. Connection represents the connection to the database.
2. DriverManager obtains the connection to the database.
3. SQLException handles SQL errors between the Java application and the database.
4. ResultSet and Statement model the data result sets and SQL statements.
38
DriverManager class
• The DriverManager class acts as an interface between user
and drivers. It keeps track of the drivers that are available and
handles establishing a connection between a database and
the appropriate driver.
• The DriverManager class maintains a list of Driver classes
that have registered themselves by calling the method
DriverManager.registerDriver().
39
Connection interface
• Connection interface resides in java.sql package and it
represents a session with a specific database you are
connecting to.
40
Statement interface
• The Statement interface provides methods to execute queries
with the database.
• The important methods of Statement interface are as follows:
1. public ResultSet executeQuery(String sql): is used to execute
SELECT query. It returns the object of ResultSet.
2. public int executeUpdate(String sql): is used to execute specified
query, it may be create, drop, insert, update, delete etc.
3. public boolean execute(String sql): is used to execute queries that
may return multiple results.
4. public int[] executeBatch(): is used to execute batch of commands.
41
ResultSet interface
• The object of ResultSet maintains a cursor pointing to a row
of a table. Initially, cursor points to before the first row.
42
PreparedStatement interface
• The PreparedStatement interface is a subinterface of
Statement. It is used to execute parameterized query.
43
Oracle Java Connectivity Demo
Requirements
• Eclipse
• JDK
• Oracle Setup
• Oracle JDBC Driver
45
Install Oracle
• Install https://www.oracle.com/database/technologies/xe-downloads.html
46
Prerequisites
• Oracle JDBC Driver
https://www.oracle.com/database/technologies/appdev/jdbc-downloads.html
47
Important to remember password
48
Connect to database
Open SQL Plus
connect sys/[password set during oracle installation]@localhost:1521/XE as sysdba;
49
Open Eclipse-> open perspective -> Database Development -> New Connection Profile -
> Oracle -> New Driver Definition -> Oracle Thin Driver -> Jar List -> provide OJDBC.jar
50
Connecting to the database
The driver class for the oracle database
is oracle.jdbc.driver.OracleDriver.
where jdbc is the API, oracle
is the database, thin is the
driver, IP address, 1521 is
the port number and XE is the
Oracle service name.
The default username for the oracle
database is system.
password given by the user at the time of
installing the oracle database.
51
CRUD Operations
Retrieve Data from Database
53
INSERT Statement
54
UPDATE Statement
55
DELETE Statement
56
MySQL Database
• Connect to MySQL database in Eclipse IDE using Database
Development perspective:
– Download MySQL https://dev.mysql.com/downloads/installer/
– Download MySQL JDBC driver
https://dev.mysql.com/downloads/connector/j/
– Create Database and Table in MySQL
– Execute SQL Statements
57
MySQL Command Line
Activities
58
Database Development perspective in
Eclipse
59
Connect Java Application with mysql
database
60
Design for Change
• Identify the functionality that may change (frequently?)
• Take special consideration in implementing such functionality in classes, so
that the changing functionality will have minimized impact on the other parts
• Use the principles of Polymorphism to provide a stable interface of the
potentially varying functionality.
Design for Change – Write to Interfaces
• The client classes are to be written in a way that they talk to the
stable interface
• Example – Handling Persistence
– Probability of change?
Example – Handling Persistence
Stude Option 1
nt
save() - Write SQL Queries
here
- Problem?
Example – Handling Persistence
Option 2
Stude DBHand
nt ler - Write SQL Queries
save() here
saveStudent(this)
- Benefits over
Option 1
- Problem?
Example – Write to Interfaces
Option 3
- Write to interfaces
- Benefits over other
Persistence options
Student Handler - Problem? When to
initialize and how?
save()
saveStudent(this)
Student PersistenceHandler
OracleDBHandler SQLPersistence
Implementation
//Student
Class Student{
PersitenceHandler persHandler;
void save(){
persHandler.saveStudent(this);
}
void setPersitenceHandler (PersitenceHandler ph)
{
this.persHandler=ph;
}
Implementation
// PersistenceHandler
Class PersistenceHandler{
abstract void saveStudent(Student s);
}
Implementation
class OracleDBHandler extends
PersistenceHandler{
void saveStudent(Student s){
//connection
//insert query formulation
//execute query
}
}
Implementation
class SQLHandler extends PersistenceHandler{
void saveStudent(Student s){
//connection
//insert query formulation
//execute query
}
}
Implementation
Main
Void main()
{
PersitenceHandler handler= new OracleHandler();
University uni= new University();
Uni. setPersitenceHandler(handler);
}
Task 02
• Add database in to your Account management system
• There should be a menu where you ask user where he wants to
store his data. Following are the options
– File
– Oracle
– MySQL
71