unit 6 java
unit 6 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.
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());
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.
}
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.
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.
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
o DriverManager class
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.
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.
import java.sql.*;
class DemoAccessData
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);
pst.setInt(1,rno);
ResultSet rs=pst.executeQuery();
if(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getString(3));
else
}
con.close();
catch(SQLException ex)
System.out.println(ex);
catch(Exception ex)
System.out.println(ex);
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);
}
}
}
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);
}
}
}