Oopj Unit-5
Oopj Unit-5
Neelima
File
A file is a named location that can be used to store related information. For example,
main.java is a Java file that contains information about the Java program.
A directory is a collection of files and subdirectories. A directory inside a directory is known
as subdirectory.
In Java, a File is an abstract data type. There are several File Operations like creating a
new File, getting information about File, writing into a File, reading from a
File and deleting a File.
A file can be classified into two types based on the way the file stores the data. They are as
follows:
• Text Files
• Binary Files
1. Text Files
A text file contains data in the form of Unicode characters and is generally used to store a
stream of characters.
• Each line in a text file ends with a new line character (‘\n’).
• It can be read or written by any text editor.
• They are generally stored with .txt file extension.
• Text files can also be used to store the source code.
2. Binary Files
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of Unicode characters.
They contain data that is stored in a similar manner to how it is stored in the main memory.
• The binary files can be created only from within a program and their contents can
only be read by a program.
• More secure as they are not easily readable.
File handling is an important part of any application. Java has several methods for creating,
reading, updating, and deleting files.
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:
Example:
import java.io.File; // Import the File class
The File class has many useful methods for creating and getting information about files.
Stream
In java, the IO operations are performed using the concept of streams. Generally, a stream
means a continuous flow of data. In java, a stream is a logical container of data that allows
us to read from and write to it. A stream can be linked to a data source, or data destination,
like a console, file or network connection by java IO system. The stream-based IO
operations are faster than normal IO operations.
In java, the stream-based IO operations are performed using two separate streams input
stream and output stream. The input stream is used for input operations, and the output
stream is used for output operations. The java stream is composed of bytes.
In Java, every program creates 3 streams automatically, and these streams are attached to
the console.
The Java streams support many different kinds of data, including simple bytes, primitive
data types, localized characters, and objects.
Java provides two types of streams, and they are as follows.
• Byte Stream
• Character Stream
The following picture shows how streams are categorized, and various built-in classes used
by the java IO system.
Character streams in Java are designed for handling the input and output of characters.
They use 16-bit Unicode characters.
Character streams are more efficient than byte streams. They are mainly used for reading
or writing to character or text-based I/O such as text files, text documents, XML, and HTML
files.
Text files are those files that are human readable. For example, a .txt file that contains
human-readable text. This file is created with a text editor such as Notepad in Windows.
Character streams that are used for reading are called readers and for writing are called
writers. They are represented by the abstract classes of Reader and Writer in Java.
Writer class
The writer class is designed to write 16-bit Unicode characters to the output stream. Since
the Writer class is an abstract class, it cannot be instantiated.
Therefore, the subclasses of the Writer class are used to write the characters onto the
output stream. The hierarchy diagram of subclasses of the Writer class is shown in the
below figure.
Writer Subclasses:
1. BufferedWriter: This class is used to write characters to the buffered output character
stream.
2. FileWriter: This output stream class writes characters to the file.
3. CharArrayWriter: This output stream class writes the characters to the character
array.
The Writer class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.
Reader class
Reader Subclasses:
1. BufferedReader: This class is used to read characters from the buffered input
character stream.
2. CharArrayReader: This class is used to read characters from the char array or
character array.
3. FileReader: This class is used to read characters (or contents) from a file.
4. FilterReader: This class is used to read characters from the underlying character input
stream.
5. InputStreamReader: This class is used to translate (or convert) bytes to characters.
6. PipeReader: This class is used to read characters from the connected piped output
stream.
7. StringReader: This class is used to read characters from a string.
8. PushBackReader: This class allows one or more characters to be returned to the input
stream.
The Reader class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.
Writing:
Using FileWriter:
import java.io.*;
class File1
{
public static void main(String args[])throws Exception
{
File f1=new File("abcd.txt");
f1.createNewFile();
FileWriter fw=new FileWriter(f1);
fw.write(78);
fw.write('\n');
fw.write('n');
fw.write('\n');
fw.write("neelima");
fw.write('\n');
char ch[]={'n','e','e','l','u'};
fw.write(ch);
System.out.println(f1.exists());
fw.close();
}
}
Using BufferedWriter:
import java.io.*;
class File2
{
public static void main(String args[])throws Exception
{
FileWriter fw=new FileWriter("abcd.txt",true);
BufferedWriter br=new BufferedWriter(fw);
br.newLine();
br.write(82);
br.newLine();
br.write('r');
br.newLine();
br.write("raghuram");
br.newLine();
char ch[]={'r','a','g','h','u'};
br.write(ch);
br.close();
}
}
Using PrintWriter:
import java.io.*;
class File3
{
public static void main(String args[])throws Exception
{
FileWriter fw=new FileWriter("abcd.txt",true);
PrintWriter pr=new PrintWriter(fw);
pr.println(82);
char ch[]={'g','a','g','a','n'};
pr.println(ch);
String str="hello";
pr.println(str);
pr.println(12.5);
pr.println(true);
pr.close();
}
}
Reading:
Using FileReader:
import java.io.*;
class FileReader1
{
public static void main(String args[]) throws Exception
{
FileReader fr=new FileReader("abcd.txt");
int i;
while((i=fr.read())!=-1)
{
System.out.print((char)i);
}
fr.close();
}
}
Using BufferedReader:
import java.io.*;
class BufferedReader1
{
public static void main(String args[]) throws Exception
{
Coping:
import java.io.*;
public class FileCopy
{
public static void main(String[] args) throws Exception
{
String sf = "abcd.txt";
String df = "12345.txt";
try
{
// Create a FileReader to read the content of the source file
r = new FileReader(sf);
// Create a FileWriter to write the content to the destination file
w = new FileWriter(df);
int c;
// Read each character from the source file and write it to the destination file
while ((c = r.read()) != -1)
{
w.write(c);
}
System.out.println("File copied successfully!");
}
catch (IOException e)
{
// Handle exceptions (file not found, read/write errors, etc.)
System.err.println("Error occurred: " + e.getMessage());
}
finally
{
try
{
Byte streams in Java are designed to provide a convenient way for handling the input and
output of bytes (i.e., units of 8-bits data). We use them for reading or writing to binary data
I/O.
Byte streams are especially used when we are working with binary files such as executable
files, image files, and files in low-level file formats such as .zip, .class, .obj, and .exe.
Binary files are those files that are machine readable. For example, a Java class file is an
extension of “.class” and humans cannot read it.
It can be processed by low-level tools such as a JVM (executable java.exe in Windows) and
java disassembler (executable javap.exe in Windows).
Another real-time example is storing a photo in a .bmp or .jpeg file. These files are certainly
not human readable. Photo editing or image manipulation software can only process them.
Byte streams that are used for reading are called input streams and for writing are
called output streams. They are represented by the abstract classes of InputStream and
OutputStream in Java.
Writing:
import java.io.FileOutputStream;
import java.io.IOException;
public class F3
{
public static void main(String[] args)
{
// Define the file path and content to write
String fp = "aout.txt";
String con = "This is a sample text written using byte streams!";
FileOutputStream w = null;
try
{
// Initialize FileOutputStream with the file path
w = new FileOutputStream(fp);
w.close();
}
catch (IOException e)
{
System.out.println("Failed to close file output stream: " + e.getMessage());
}
}
}
}
Reading:
import java.io.FileInputStream;
import java.io.IOException;
public class F4
{
public static void main(String[] args)
{
// Define the file path to read from
String fp = "aout.txt";
FileInputStream r = null;
try
{
// Initialize FileInputStream with the file path
r = new FileInputStream(fp);
Coping:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class F5
{
public static void main(String[] args)
{
// Source and destination file paths
String sf = "aout.txt";
String df = "ain.txt";
FileInputStream r = null;
FileOutputStream w = null;
try
{
// Open input and output streams for source and destination files
r = new FileInputStream(sf);
w = new FileOutputStream(df);
try
{
if (r != null)
r.close();
if (w != null)
w.close();
}
catch (IOException e)
{
System.out.println("Failed to close file streams: " + e.getMessage());
}
}
}
}
************
Java Database Connectivity (JDBC) is a Java API that allows Java applications to interact
with databases in a seamless and standardized manner. By providing a set of classes and
interfaces, JDBC enables developers to connect to a database, execute SQL queries, and
retrieve or manipulate data programmatically.
Purpose of JDBC:
JDBC was introduced to address the need for a portable, database-independent solution for
Java applications to work with databases. It abstracts database-specific details and provides
a unified interface for all database interactions.
JDBC is extensively used in web and enterprise applications where persistent data storage
and retrieval are essential. Examples include:
Applications that require real-time data to make decisions can leverage JDBC to query
databases dynamically.
• For example, inventory management systems that update stock levels based on real-
time sales data.
3. Data Migration:
JDBC can be used for transferring data between different databases or exporting data to
external formats.
JDBC enables data retrieval for creating custom reports and performing analytics.
Advantages of JDBC:
1. Ease of Use:
o JDBC simplifies the process of connecting to databases and executing queries
through a straightforward API.
2. Flexibility:
o With its support for multiple databases and dynamic queries, JDBC can handle a
variety of use cases.
3. Integration with Java Ecosystem:
o JDBC integrates seamlessly with other Java frameworks and technologies, such
as Hibernate, Spring, and Java EE.
While JDBC is a powerful tool, developers may face challenges such as:
Real-World Example:
Suppose an online bookstore wants to display the details of all books in its catalog. Using
JDBC:
Structure of JDBC
Core Components:
Workflow:
JDBC Architecture
Two-Tier Architecture
1. Structure:
o Direct communication between client (user’s application) and the database
(data source).
o No intermediary layer.
2. How it works:
o User commands go directly to the database, and results are returned directly
to the user.
3. Example:
o A Java application directly querying a MySQL database using a JDBC driver.
4. Limitations:
o Harder to control access to data.
o Deployment changes require updates to every client.
o Performance issues with many clients.
Three-Tier Architecture
1. Structure:
o Involves three layers:
▪ Client (user’s application).
▪ Middle Tier (services like business logic, API, or application server).
▪ Database (data source).
2. How it works:
o User commands are sent to the middle tier.
o The middle tier processes these commands and communicates with the
database.
o Results from the database are passed back through the middle tier to the
user.
3. Example:
o A Java application sends requests to an application server (middle tier),
which interacts with the database.
4. Advantages:
o Easier to manage and secure access to the database.
o Simplifies updates and deployment (changes are centralized in the middle
tier).
o Better performance when handling multiple users.
1. Application Layer:
Role: This is the topmost layer and represents the Java program written by the developer.
It contains the application logic that interacts with the database to perform tasks like data
retrieval, updates, and deletions.
Responsibilities:
Example: A Java application that retrieves product details from a database for an e-
commerce platform.
Role: This layer provides a standardized set of interfaces and classes in the java.sql package.
It acts as a bridge between the application and the database-specific JDBC drivers.
Responsibilities:
• Facilitating communication between the Java application and the JDBC driver.
• Abstracting database-specific details from the application, making it independent of
the database.
Key Components:
Role: This layer consists of the JDBC drivers that convert API calls from the application
into database-specific calls. Each database system requires its own JDBC driver.
Responsibilities:
• Translating JDBC API methods into SQL commands understood by the database.
• Establishing a connection with the database.
Driver Types:
Example:
4. Database Layer:
Role: This is the actual database system where the data resides. It processes the SQL
queries sent by the driver and returns the results back to the application.
Responsibilities:
Examples of Databases:
1. Application Layer:
• The user interacts with the Java application, which sends a request to perform an
operation on the database (e.g., retrieve employee records).
• Example: The Java application contains a query like:
• The API receives this query and interacts with the DriverManager to establish a
connection to the database.
• Example: The application uses the DriverManager.getConnection() method.
• The JDBC driver converts the standardized API calls into database-specific calls.
• It communicates with the database using the appropriate protocol (e.g., SQL over
TCP/IP for MySQL).
4. Database Layer:
• The database executes the query and sends the result back to the driver.
• Example: A MySQL database fetches the requested rows from the employees table.
5. Reverse Communication:
• The driver converts the database-specific results into a format compatible with the
JDBC API (e.g., ResultSet).
• The Java application processes the ResultSet and displays the data to the user.
Thin
Driver
This driver acts as a bridge between JDBC and ODBC. It converts JDBC calls to ODBC calls,
which are then sent to the database. It requires an ODBC driver to be configured on the
system. This type is now deprecated and not recommended for modern applications.
Advantages Disadvantages
- Platform-dependent; requires ODBC driver
- Easy to set up and use for beginners.
setup.
- Provides access to any ODBC-compliant - Poor performance due to multiple layers of
database. translation.
- Deprecated and no longer supported in Java 8
and beyond.
This driver uses database vendor-specific native libraries to convert JDBC calls into
database-specific calls. The native libraries must be installed on the client machine. While
it offers better performance than Type 1, it is not portable due to its dependency on
platform-specific native code.
Advantages Disadvantages
- Better performance than Type 1 due - Platform-dependent; requires database-specific
to fewer layers. native libraries installed.
- Deployment and maintenance are challenging on
- Supports database-specific features.
multiple platforms.
- Not portable; tied to the specific database and
operating system.
This driver communicates with the database through a middleware server. The middleware
translates the JDBC calls into database-specific protocol calls. It is platform-independent
and ideal for web-based applications where remote database access is required.
Advantages Disadvantages
- Platform-independent; no client-side - Requires additional middleware, increasing
dependencies. setup complexity.
- Adds latency due to communication with
- Supports remote access to databases.
middleware.
- Middleware can handle connection - Maintenance overhead for middleware
pooling and caching. server.
This driver directly converts JDBC calls into database-specific network protocol calls. It is
written entirely in Java, making it platform-independent. No additional software or
middleware is required, making it the most commonly used driver for modern applications.
Advantages Disadvantages
- Fast and lightweight due to direct - Database-specific; a separate driver is required
communication. for each database type.
- Platform-independent; works on any - May lack advanced features compared to
system with Java. middleware-based solutions.
- No additional software or middleware
needed.
Comparison Table:
Platform
Type Translation Layer Performance Use Case Example
Independence
JDBC → ODBC → Microsoft Access with
Type 1 No Slow
Database ODBC driver
JDBC → Native API Faster than Oracle with OCI
Type 2 No
→ Database Type 1 driver
JDBC →
Type 3 Middleware → Yes Moderate IDS Server
Database
JDBC → Database MySQL Connector/J,
Type 4 Yes Fastest
(Direct) PostgreSQL
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
// Step 1: Load the MySQL driver
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation of the Program:
1. Load the Driver:
• Class.forName("com.mysql.cj.jdbc.Driver"); loads the MySQL driver into memory.
2. Establish Connection:
• DriverManager.getConnection() creates a session with the database.
3. Create Statement:
• A Statement object is used to send SQL queries to the database.
4. Execute Query:
• executeQuery() runs the SQL query and returns a ResultSet.
5. Process ResultSet:
• The data from the database is iterated and displayed.
6. Close Resources:
• Ensures connections and resources are properly released.
To connect to the database, you first need to load or register the driver.
Syntax Options:
Class.forName("url");
DriverManager.registerDriver(new Driver("url"));
System.setProperty("url");
Syntax:
Syntax:
Statement st = con.createStatement();
PreparedStatement ps = con.prepareStatement("sql query");
CallableStatement cs = con.prepareCall("stored procedure");
Syntax:
Use the ResultSet interface to handle results of a SELECT query. The ResultSet maintains a
cursor to traverse rows.
Syntax:
Syntax:
con.close();
st.close();
rs.close();
Below are the programs to demonstrate various JDBC operations, each with an appropriate
heading.
Establishing a Connection
import java.sql.*;
Inserting Data
import java.sql.*;
Updating Data
import java.sql.*;
Deleting Data
import java.sql.*;
Selecting Data
import java.sql.*;
************