0% found this document useful (0 votes)
8 views20 pages

Java Sec D

File handling in Java involves creating, reading, writing, updating, and deleting files using the java.io package, which treats files as streams of data. Java supports both byte and character streams for handling different types of data, and provides classes like FileInputStream, FileOutputStream, FileReader, and FileWriter for these operations. JDBC (Java Database Connectivity) allows Java applications to interact with databases, executing SQL queries and processing results through a layered architecture and various driver types.

Uploaded by

jainnamit34
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)
8 views20 pages

Java Sec D

File handling in Java involves creating, reading, writing, updating, and deleting files using the java.io package, which treats files as streams of data. Java supports both byte and character streams for handling different types of data, and provides classes like FileInputStream, FileOutputStream, FileReader, and FileWriter for these operations. JDBC (Java Database Connectivity) allows Java applications to interact with databases, executing SQL queries and processing results through a layered architecture and various driver types.

Uploaded by

jainnamit34
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

File Handling

File handling in Java refers to the process of creating, reading, writing, updating, and
deleting files stored on secondary storage (hard disk).
Since programs often need to store data permanently, Java provides a powerful and
secure I/O (Input/Output) system through the [Link] package.

Java treats files as streams of data, allowing programs to read data from a source or write
data to a destination.

Need for File Handling


• To store data permanently (data persistence).
• To read large data that cannot fit into memory.
• To share data between different programs.
• To maintain logs, reports, and configuration files.
• To support real-world applications like banking, billing, student records, etc.

Java I/O Stream Concept


Java uses the concept of streams to handle file operations.

Stream

A stream is a sequence of data flowing from a source to a destination.

There are two main types:

1. Input Stream → Reads data from file


2. Output Stream → Writes data to file

Types of Streams in Java

1️⃣ Byte Stream

• Handles data byte by byte


• Used for binary files (images, audio, video)
• Base classes:
o InputStream
o OutputStream

Common Classes:

• FileInputStream
• FileOutputStream

2️⃣ Character Stream

• Handles data character by character


• Used for text files
• Supports Unicode
• Base classes:
o Reader
o Writer

Common Classes:

• FileReader
• FileWriter
• BufferedReader
• BufferedWriter

File Class in Java


The File class (from [Link]) is used to create, delete, and get information about files and
directories.

Common Methods of File Class

• createNewFile()
• delete()
• exists()
• getName()
• getPath()
• length()
• mkdir()
Example:

File f = new File("[Link]");


[Link]([Link]());

Reading Data from a File

Using FileReader

FileReader fr = new FileReader("[Link]");


int ch;
while((ch = [Link]()) != -1) {
[Link]((char)ch);
}
[Link]();

Using BufferedReader (Efficient)

BufferedReader br = new BufferedReader(new FileReader("[Link]"));


String line;
while((line = [Link]()) != null) {
[Link](line);
}
[Link]();

Writing Data to a File

Using FileWriter

FileWriter fw = new FileWriter("[Link]");


[Link]("Welcome to Java File Handling");
[Link]();

Using BufferedWriter

BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]"));


[Link]("Hello Java");
[Link]();
[Link]("File Handling Example");
[Link]();

Appending Data to a File


FileWriter fw = new FileWriter("[Link]", true);
[Link]("\nNew Data Added");
[Link]();

Exception Handling in File Operations


File handling may cause runtime errors such as:

• File not found


• Permission denied
• I/O errors

Hence, Java uses try–catch blocks or throws IOException.

Example:

try {
FileReader fr = new FileReader("[Link]");
} catch(IOException e) {
[Link](e);
}

Serialization in Java
Serialization is the process of converting an object into a byte stream to store it in a file.

• Uses ObjectOutputStream and ObjectInputStream


• Interface used: Serializable

Advantages of File Handling in Java


• Platform independent
• Secure and robust
• Supports both text and binary files
• Efficient using buffered streams
• Integrates well with exception handling

Limitations
• Slower than in-memory operations
• Requires proper exception handling
• File corruption risk if not closed properly

FileInputStream and FileOutputStream


In Java, file handling allows programs to read data from and write data to files stored on
secondary storage (disk).
For handling binary data (such as images, audio files, videos, PDFs, or raw bytes), Java
provides byte stream classes.
Two important byte stream classes are:

• FileInputStream
• FileOutputStream

Both belong to the package [Link].

FileInputStream
FileInputStream is a Java class used to read data from a file byte by byte.
It is mainly used when dealing with binary files rather than text files.

Purpose / Use

• To read binary data from a file.


• To read raw bytes stored in a file.
• Commonly used for images, audio files, executable files, etc.

Class Declaration

FileInputStream fis = new FileInputStream("filename");


Important Methods

Method Description
read() Reads one byte of data
read(byte[] b) Reads data into a byte array
available() Returns number of bytes
available
close() Closes the input stream

Example

import [Link].*;

class ReadFile {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("[Link]");
int ch;
while((ch = [Link]()) != -1) {
[Link]((char)ch);
}
[Link]();
}
}

Key Points

• Reads data sequentially


• Returns -1 at end of file
• Throws FileNotFoundException or IOException

FileOutputStream
FileOutputStream is a Java class used to write data to a file byte by byte.
If the file does not exist, it creates a new file.

Purpose / Use

• To write binary data to a file.


• To store raw bytes in files.
• Used for writing images, audio files, logs, etc.
Class Declaration

FileOutputStream fos = new FileOutputStream("filename");

Important Methods

Method Description
write(int b) Writes one byte
write(byte[] b) Writes byte array
flush() Forces writing of data
close() Closes the output
stream

Example

import [Link].*;

class WriteFile {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("[Link]");
String msg = "Hello Java File Handling";
byte[] b = [Link]();
[Link](b);
[Link]();
[Link]("Data written successfully");
}
}

Key Points

• Overwrites file by default


• Can append data using:

new FileOutputStream("[Link]", true);


Difference Between FileInputStream and
FileOutputStream
Aspect FileInputStream FileOutputStream
Purpose Reads data from file Writes data to file
Direction File → Program Program → File
Data Type Byte (binary) Byte (binary)
Used For Input operations Output operations
File Creation Does not create file Creates file if not exists

Advantages
• Suitable for binary file handling
• Efficient for raw byte processing
• Part of core Java I/O library

Limitations
• Not ideal for text files (better use FileReader / FileWriter)
• No built-in buffering (buffered streams needed for performance)

BufferedInputStream and
BufferedOutputStream
In Java, file input and output operations using FileInputStream and FileOutputStream
directly access the disk. Disk access is slow, and reading or writing byte-by-byte reduces
performance.
To overcome this problem, Java provides buffered streams, namely
BufferedInputStream and BufferedOutputStream, which improve I/O efficiency by using
an internal memory buffer.

These classes belong to the [Link] package and are examples of byte-oriented buffered
streams.

BufferedInputStream
BufferedInputStream is a class that wraps an InputStream (such as FileInputStream) and
reads data into a buffer.
Instead of reading one byte at a time from the file, it reads a block of bytes into memory
and then supplies bytes from the buffer.

Why it is Used

• Reduces the number of disk access operations


• Improves input performance
• Efficient for reading large files

Constructors

BufferedInputStream(InputStream in)
BufferedInputStream(InputStream in, int bufferSize)

Working

1. Data is read from the file into an internal buffer.


2. Program reads bytes from the buffer.
3. Disk is accessed only when the buffer becomes empty.

Example

import [Link].*;

class ReadFile {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("[Link]");
BufferedInputStream bis = new BufferedInputStream(fis);

int ch;
while ((ch = [Link]()) != -1) {
[Link]((char) ch);
}

[Link]();
[Link]();
}
}
Advantages

• Faster than FileInputStream


• Efficient memory usage
• Suitable for large files

BufferedOutputStream
BufferedOutputStream is a class that wraps an OutputStream (such as
FileOutputStream) and writes data to an internal buffer before sending it to the file.

Why it is Used

• Improves output performance


• Reduces frequent disk writes
• Writes data in chunks instead of byte-by-byte

Constructors

BufferedOutputStream(OutputStream out)
BufferedOutputStream(OutputStream out, int bufferSize)

Working

1. Data is written to the buffer.


2. Buffer stores data temporarily.
3. Data is written to the file when:
a. Buffer is full
b. flush() is called
c. Stream is closed

Example

import [Link].*;

class WriteFile {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("[Link]");
BufferedOutputStream bos = new BufferedOutputStream(fos);
String msg = "Buffered Output Stream Example";
[Link]([Link]());

[Link](); // forces data to file


[Link]();
[Link]();
}
}

Advantages

• Faster file writing


• Reduces I/O overhead
• Efficient handling of large data

Difference Between Buffered and Unbuffered Streams


Feature FileInputStream / BufferedInputStream /
FileOutputStream BufferedOutputStream
Disk Access Frequent Less frequent
Speed Slower Faster
Buffer No buffer Uses buffer
Performance Lower Higher
Suitable for Large Less efficient Highly efficient
Files

JDBC (Java Database Connectivity)


JDBC (Java Database Connectivity) is a standard Java API that allows Java programs to
connect with databases, execute SQL queries, and process the results.
It acts as a bridge between Java applications and relational databases such as MySQL,
Oracle, PostgreSQL, etc.

JDBC enables Java to perform database operations like Create, Read, Update, and
Delete (CRUD) in a database-independent manner.

Why JDBC is Needed


• Java programs cannot directly communicate with databases.
• JDBC provides a uniform interface to access different databases.
• It allows Java applications to be dynamic and data-driven.
• Essential for enterprise applications, web applications, and desktop software.

JDBC Architecture
JDBC follows a layered architecture:

Java Application

JDBC API

JDBC Driver Manager

JDBC Driver

Database

Explanation:

• Java Application sends SQL requests.


• JDBC API provides methods for database access.
• Driver Manager loads and manages JDBC drivers.
• JDBC Driver translates Java calls into database-specific calls.
• Database executes SQL queries and returns results.

JDBC Drivers
JDBC drivers are software components that enable Java applications to interact with
databases.

Types of JDBC Drivers

1. Type 1 – JDBC-ODBC Bridge Driver

• Uses ODBC driver to access databases.


• Platform dependent.
• Slower and deprecated.
2. Type 2 – Native API Driver

• Uses database-specific native libraries.


• Faster than Type 1.
• Platform dependent.

3. Type 3 – Network Protocol Driver

• Uses middleware server.


• Platform independent.
• More secure.

4. Type 4 – Thin Driver

• Pure Java driver.


• Directly communicates with database.
• Platform independent and fastest.
• Most commonly used (e.g., MySQL Connector/J).

JDBC Core Components

1. DriverManager

• Manages JDBC drivers.


• Establishes connection between Java application and database.

[Link]()

2. Connection Interface

• Represents a connection to the database.


• Required to execute SQL statements.

Connection con = [Link](url, user, password);

3. Statement Interface

Used to execute SQL queries.

Types:

• Statement – Simple SQL queries.


• PreparedStatement – Precompiled queries (more secure).
• CallableStatement – Used for stored procedures.

Statement stmt = [Link]();

4. ResultSet

• Stores results returned by SELECT queries.


• Allows traversal of records row by row.

ResultSet rs = [Link]("SELECT * FROM student");

Steps to Connect, Create, Insert,


Manipulate and Delete Data in Database
using Java (JDBC)
Step 1: Load and Register JDBC Driver
The driver enables Java to communicate with the database.

Example (MySQL):

[Link]("[Link]");

This step loads the driver into memory.


In modern JDBC, this step may be optional but still preferred for exams.

Step 2: Establish Database Connection


Create a connection between Java program and database.

Syntax:

Connection con = [Link](


"jdbc:mysql://localhost:3306/dbname", "username", "password");
Example:

Connection con = [Link](


"jdbc:mysql://localhost:3306/studentdb", "root", "root");

If connection is successful, Java can now access the database.

Step 3: Create Statement Object


Used to send SQL commands to the database.

Types:

• Statement
• PreparedStatement
• CallableStatement

Example:

Statement stmt = [Link]();

Database Operations Using JDBC

Step 4: Create Table


Used to create database tables.

SQL:

CREATE TABLE student (


id INT,
name VARCHAR(50),
marks INT
);
Java Code:

String sql = "CREATE TABLE student(id INT, name VARCHAR(50), marks INT)";
[Link](sql);

executeUpdate() is used for CREATE, INSERT, UPDATE, DELETE.

Step 5: Insert Data into Table


Adds records into the database.

SQL:

INSERT INTO student VALUES (1, 'Amit', 85);

Java Code:

String sql = "INSERT INTO student VALUES (1, 'Amit', 85)";


[Link](sql);

Using PreparedStatement:

PreparedStatement ps = [Link](
"INSERT INTO student VALUES (?, ?, ?)");
[Link](1, 2);
[Link](2, "Neha");
[Link](3, 90);
[Link]();

Prevents SQL injection


Faster for repeated execution
Step 6: Retrieve / Read Data (SELECT)
Used to fetch records from database.

SQL:

SELECT * FROM student;

Java Code:

ResultSet rs = [Link]("SELECT * FROM student");

while([Link]()) {
[Link](
[Link]("id") + " " +
[Link]("name") + " " +
[Link]("marks")
);
}

executeQuery() returns a ResultSet


[Link]() moves cursor row by row

Step 7: Update (Manipulate) Data


Used to modify existing records.

SQL:

UPDATE student SET marks = 95 WHERE id = 1;

Java Code:

String sql = "UPDATE student SET marks = 95 WHERE id = 1";


[Link](sql);
Used to change values without deleting records.

Step 8: Delete Data


Removes records from the database.

SQL:

DELETE FROM student WHERE id = 2;

Java Code:

String sql = "DELETE FROM student WHERE id = 2";


[Link](sql);

Permanently deletes data.

Step 9: Close JDBC Resources


Always close resources to avoid memory leaks.

Example:

[Link]();
[Link]();
[Link]();

Closing order: ResultSet → Statement → Connection

• PreparedStatement
• PreparedStatement is used to execute parameterized SQL queries.
It improves performance and prevents SQL Injection attacks.

Example:

• PreparedStatement ps =
[Link]("INSERT INTO student VALUES (?, ?)");
[Link](1, 101);
[Link](2, "Amit");

[Link]();

Advantages:

• Faster execution.
• More secure.
• Avoids SQL injection.
• Reusable.

CallableStatement
• Used to call stored procedures in the database.
• CallableStatement cs =
[Link]("{call getStudent()}");
[Link]();

JDBC Exception Handling


• JDBC uses SQLException to handle database-related errors.
• catch(SQLException e) {
[Link]();
}

Advantages of JDBC
• Platform independent.
• Database independent.
• Secure and reliable.
• Supports large enterprise applications.
• Easy integration with Java frameworks.

Limitations of JDBC
• Requires SQL knowledge.
• Complex code for large projects.
• Manual resource management.
• Performance overhead if not optimized.

Applications of JDBC
• Web applications (Servlets, JSP).
• Banking systems.
• Inventory management systems.
• Student management systems.
• Enterprise software.

You might also like