0% found this document useful (0 votes)
4 views

unit 6 java

The document provides an overview of file operations in Java, including creating, reading, writing, and deleting files, as well as serialization and deserialization of objects. It also covers Java Database Connectivity (JDBC), detailing its purpose, types of JDBC drivers, and the steps to connect a Java application to a database. Examples of code snippets for various operations are included to illustrate the concepts discussed.

Uploaded by

mrmayurffyt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

unit 6 java

The document provides an overview of file operations in Java, including creating, reading, writing, and deleting files, as well as serialization and deserialization of objects. It also covers Java Database Connectivity (JDBC), detailing its purpose, types of JDBC drivers, and the steps to connect a Java application to a database. Examples of code snippets for various operations are included to illustrate the concepts discussed.

Uploaded by

mrmayurffyt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Unit VI – File I/O and JDBC

File Operations in Java

In Java, a File is an abstract data type. A named location used to store related information is
known as a File. 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.

Before understanding the File operations, it is required that we should have knowledge
of Stream and File methods. If you have knowledge about both of them, you can skip it.

File Operations
We can perform the following operation on a file:

o Create a File
o Get File Information
o Write to a File
o Read from a File
o Delete a File

Create a File
Create a File operation is performed to create a new file. We use the createNewFile() method
of file. The createNewFile() method returns true when it successfully creates a new file and
returns false when the file already exists.

Let's take an example of creating a file to understand how we can use


the createNewFile() method to perform this operation.

// Importing File class


import java.io.File;
// Importing the IOException class for handling errors
import java.io.IOException;
class CreateFile {
public static void main(String args[]) {
try {
// Creating an object of a file
File f0 = new File("D:FileOperationExample.txt");
if (f0.createNewFile()) {
System.out.println("File " + f0.getName() + " is created successfully.");
} else {
System.out.println("File is already exist in the directory.");
}
} catch (IOException exception) {
System.out.println("An unexpected error is occurred.");
exception.printStackTrace();
}
}
}
In the above code, we import the File and IOException class for performing file operation and handling
errors, respectively. We create the f0 object of the File class and specify the location of the directory where
we want to create a file. In the try block, we call the createNewFile() method through the f0 object to create
a new file in the specified location. If the method returns false, it will jump to the else section. If there is
any error, it gets handled in the catch block.

Get File Information

The operation is performed to get the file information. We use several methods to get the information about
the file like name, absolute path, is readable, is writable and length.
Let's take an example to understand how to use file methods to get the information of the file.
// Import the File class
import java.io.File;
class FileInfo {
public static void main(String[] args) {
// Creating file object
File f0 = new File("D:FileOperationExample.txt");
if (f0.exists()) {
// Getting file name
System.out.println("The name of the file is: " + f0.getName());

// Getting path of the file


System.out.println("The absolute path of the file is: " + f0.getAbsolutePath());

// Checking whether the file is writable or not


System.out.println("Is file writeable?: " + f0.canWrite());
// Checking whether the file is readable or not
System.out.println("Is file readable " + f0.canRead());

// Getting the length of the file in bytes


System.out.println("The size of the file in bytes is: " + f0.length());
} else {
System.out.println("The file does not exist.");
}
}
}
In the above code, we import the java.io.File package and create a class FileInfo. In the main
method, we create an object of the text file which we have created in our previous example. We
check the existence of the file using a conditional statement, and if it is present, we get the following
information about that file:
1. We get the name of the file using the getName()
2. We get the absolute path of the file using the getAbsolutePath() method of the file.
3. We check whether we can write data into a file or not using the canWrite()
4. We check whether we can read the data of the file or not using the canRead()
5. We get the length of the file by using the length()

Write to a File
The next operation which we can perform on a file is "writing into a file". In order to write
data into a file, we will use the FileWriter class and its write() method together. We need to
close the stream using the close() method to retrieve the allocated resources.

Let's take an example to understand how we can write data into a file.

// Importing the FileWriter class


import java.io.FileWriter;

// Importing the IOException class for handling errors


import java.io.*;
class DemoFileWriter
{
public static void main(String args[])
{
try
{
File f=new File("D:/abc.txt");
if(f.exists())
{
FileWriter fw=new FileWriter(f);
fw.write("Hello, this is my new text file.");
fw.close();
}

}
catch(IOException e)
{
System.out.println(e);
}
}
}
Read from a File
The next operation which we can perform on a file is "read from a file". In order to read data from file we
will use FileReader class. FileReader class provides predefined method read().
Let's take an example to understand how we can read data from a file.
import java.io.*;
class DemoFileReader
{
public static void main(String args[])
{
try
{
File f=new File("D:/tanaji.txt");
if(f.exists())
{
FileReader fr=new FileReader(f);
int c;
while((c=fr.read())!=-1)
{
System.out.print((char)c);
}
fr.close();
}

}
catch(IOException e)
{
System.out.println(e);
}
}
}
Serialization and Deserialization in Java
Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is
mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.

The reverse operation of serialization is called deserialization where byte-stream is converted


into an object. The serialization and deserialization process is platform-independent, it means
you can serialize an object on one platform and deserialize it on a different platform.

For serializing the object, we call the writeObject() method of ObjectOutputStream class, and
for deserialization we call the readObject() method of ObjectInputStream class.

We must have to implement the Serializable interface for serializing the object.

java.io.Serializable interface

Serializable is a marker interface (has no data member and method). It is used to "mark" Java
classes so that the objects of these classes may get a certain capability.
The Cloneable and Remote are also marker interfaces.

The Serializable interface must be implemented by the class whose object needs to be
persisted.

Let's see the example given below to serialize object:

import java.io.*;
class Student implements Serializable
{
int rno;
String sname;
Student(int no,String name)
{
rno=no;
sname=name;
}
void getData()
{
System.out.println(rno+" "+sname);
}
}

class DemoSerializable
{
public static void main(String args[])
{
try
{
FileOutputStream fo=new FileOutputStream("abc");
ObjectOutputStream os=new ObjectOutputStream(fo);
Student s=new Student(20,"XYZ");
os.writeObject(s);
//os.flush();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Example of Java Deserialization
Deserialization is the process of reconstructing the object from the serialized state. It is the
reverse operation of serialization. Let's see an example where we are reading the data from a
deserialized object.

import java.io.*;
class Student implements Serializable
{
int rno;
String sname;
Student(int no,String name)
{
rno=no;
sname=name;
}
void getData()
{
System.out.println(rno+" "+sname);
}
}

class DemoDeserializable
{
public static void main(String args[])
{
try
{
FileInputStream fi=new FileInputStream("abc");
ObjectInputStream os=new ObjectInputStream(fi);
Student s=(Student)os.readObject();
s.getData();
}
catch(IOException e)
{
System.out.println(e);
}
catch(ClassNotFoundException e)
{
}
}
}
Java JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database.

We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.
The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based on
the X/Open SQL Call Level Interface. The java.sql package contains classes and interfaces for JDBC
API. A list of popular interfaces of JDBC API are given below:

o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface

A list of popular classes of JDBC API are given below:

o DriverManager class

Types of JDBC Drivers


JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver
converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin driver.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you
use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.

Advantages:
o easy to use.
o can be easily connected to any database.

Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function calls.
o The ODBC driver needs to be installed on the client machine.

2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into native calls of the database API. It is not written entirely in java.

Advantage:
o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.

3) Network Protocol driver


The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.

Advantage:
o No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.

Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-specific
coding to be done in the middle tier.

4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is
known as thin driver. It is fully written in Java language.

Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.

Disadvantage:
o Drivers depend on the Database.

Java Database Connectivity with 5 Steps


There are 5 steps to connect any java application with the database using JDBC. These steps are as
follows:
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to dynamically
load the driver class.

Syntax of forName() method


public static void forName(String className)throws ClassNotFoundException

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with the database.

Syntax of getConnection() method


public static Connection getConnection(String url,String name,String password)
throws SQLException

3) Create the Statement object


To create SQL query we use three interfaces. 1)Statement 2)PreparedStatement 3)CallableStatement

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the database. This method
returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method


public ResultSet executeQuery(String sql)throws SQLException

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically. The close() method of Connectio
used to close the connection.

Syntax of close() method


public void close()throws SQLException

Example for accessing data from MySql Database

import java.sql.*;

class DemoAccessData

public static void main(String args[])


{

try

int rno=Integer.parseInt(args[0]);

String url="jdbc:mysql://localhost:3306/student_db";

String uname="root";

String pwd="cocsit";

Class.forName("com.mysql.cj.jdbc.Driver");

Connection con=DriverManager.getConnection(url,uname,pwd);

PreparedStatement pst=con.prepareStatement("select * from


stud_details where rno=?");

pst.setInt(1,rno);

ResultSet rs=pst.executeQuery();

if(rs.next())

System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getString(3));

else

System.out.println("Record not found");

}
con.close();

catch(SQLException ex)

System.out.println(ex);

catch(Exception ex)

System.out.println(ex);

Example for inserting data into MySql Database

import java.sql.*;
class DemoInsertData
{
public static void main(String args[])
{
try
{
int rno=Integer.parseInt(args[0]);
String sname=args[1];
String saddress=args[2];
String url="jdbc:mysql://localhost:3306/student_db";
String uname="root";
String pwd="cocsit";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection(url,uname,pwd);
PreparedStatement pst=con.prepareStatement("insert into stud_details
values(?,?,?)");
pst.setInt(1,rno);
pst.setString(2,sname);
pst.setString(3,saddress);
int count=pst.executeUpdate();
if(count>0)
{
System.out.println("Record Inserted Successfully");
}
else
{
System.out.println("Record Insertation Failed");
}

con.close();
}
catch(SQLException ex)
{
System.out.println(ex);
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}

Example for updating data from MySql Database

import java.sql.*;
class DemoUpdateData
{
public static void main(String args[])
{
try
{
int rno=Integer.parseInt(args[0]);
String sname=args[1];
String saddress=args[2];
String url="jdbc:mysql://localhost:3306/student_db";
String uname="root";
String pwd="cocsit";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection(url,uname,pwd);
PreparedStatement pst=con.prepareStatement("update stud_details set
sname=?, saddress=? where rno=?");
pst.setInt(3,rno);
pst.setString(1,sname);
pst.setString(2,saddress);
int count=pst.executeUpdate();
if(count>0)
{
System.out.println("Record Updated Successfully");
}
else
{
System.out.println("Record Updation Failed");
}
con.close();
}
catch(SQLException ex)
{
System.out.println(ex);
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}

Example for deleting data from MySql Database


import java.sql.*;
class DemoDeleteData
{
public static void main(String args[])
{
try
{
int rno=Integer.parseInt(args[0]);
String url="jdbc:mysql://localhost:3306/student_db";
String uname="root";
String pwd="cocsit";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection(url,uname,pwd);
PreparedStatement pst=con.prepareStatement("delete from stud_details
where rno=?");
pst.setInt(1,rno);
int count=pst.executeUpdate();
if(count>0)
{
System.out.println("Record Deleted Successfully");
}
else
{
System.out.println("Record Delation Failed");
}
con.close();
}
catch(SQLException ex)
{
System.out.println(ex);
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}

You might also like