SDA-Lect08-Fall2024-File Handling and DB
SDA-Lect08-Fall2024-File Handling and DB
CS-3004
Lecture#07
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).
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”);
9
Useful File Methods
10
Create a File
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.*;
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.
16
Basic IO Algorithm
• Reading • Writing
17
Byte Streams
• Read and write 8-bit
bytes
• InputStream and
OutputStream are
abstract super
classes
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
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
BufferedReader BufferedInputStream
BufferedWriter BufferedOutputStream
Character Byte Streams
Streams
26
Using Buffer Streams
import java.io.*;
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
• 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.
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).
33
JDBC Drivers
Java Application
• JDBC consists of two parts: JDBC API
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
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.
39
Connection interface
40
Statement interface
• The Statement interface provides methods to execute queries
with the database.
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
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.
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
• The client classes are to be written in a way that they talk to the
stable interface
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
Student PersistenceHandler
OracleDBHandler SQLPersistence
Implementation
//Student
Class Student{
PersitenceHandler persHandler;
void save(){
persHandler.saveStudent(this);
}
// PersistenceHandler
Class PersistenceHandler{
abstract void saveStudent(Student s);
}
Implementation
Main
Void main()
{
PersitenceHandler handler= new OracleHandler();
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