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

File Handling in Java Using Filewriter and Filereader

The document discusses File handling in Java using FileWriter and FileReader classes. It explains that FileWriter and FileReader classes are used to write and read data from text files as they are character stream classes, unlike FileInputStream and FileOutputStream which are byte stream classes. It provides details about FileWriter, which is used to create a file and write characters to it, and FileReader, which is used to read data in character form from a text file. Code examples are given to demonstrate how to create a text file using FileWriter and how to read from it using FileReader. The document also discusses Java date and time classes, regular expressions in Java, serialization and deserialization, and JDBC for database connectivity in
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)
75 views

File Handling in Java Using Filewriter and Filereader

The document discusses File handling in Java using FileWriter and FileReader classes. It explains that FileWriter and FileReader classes are used to write and read data from text files as they are character stream classes, unlike FileInputStream and FileOutputStream which are byte stream classes. It provides details about FileWriter, which is used to create a file and write characters to it, and FileReader, which is used to read data in character form from a text file. Code examples are given to demonstrate how to create a text file using FileWriter and how to read from it using FileReader. The document also discusses Java date and time classes, regular expressions in Java, serialization and deserialization, and JDBC for database connectivity in
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
You are on page 1/ 32

File handling in Java using FileWriter and FileReader

Java FileWriter and FileReader classes are used to write and read data from text files (they
are Character Stream classes). It is recommended not to use the FileInputStream and
FileOutputStream classes if you have to read and write any textual information as these are
Byte stream classes.
FileWriter
FileWriter is useful to create a file writing characters into it.

 This class inherits from the OutputStream class.


 FileWriter is meant for writing streams of characters. For writing streams of raw bytes,
consider using a FileOutputStream.
 FileWriter creates the output file , if it is not present already.

Following program depicts how to create a text file using FileWriter

import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.FileNotFoundException;

public class WriteFile {


public static void main(String[] args) throws FileNotFoundException {
FileOutputStream fos = new FileOutputStream("myFile.txt");
PrintWriter pw=new PrintWriter(fos);
pw.println("I love java");
pw.close();
}
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


FileReader
FileReader is useful to read data in the form of characters from a ‘text’ file.
 This class inherit from the InputStreamReader Class.
 FileReader is meant for reading streams of characters. For reading streams of raw bytes,
consider using a FileInputStream.

import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.util.Scanner;
public class ReadFile
{
public static void main(String[] args) throws FileNotFoundException
{
FileInputStream fis=new FileInputStream("myFile.txt");
Scanner in=new Scanner(fis);
while(in.hasNext()){
System.out.println(in.nextLine());
}
}
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Java Date and Time
Java does not have a built-in Date class, but we can import the java.time package to work with
the date and time API. The package includes many date and time classes. For example:

Class Description

LocalDate Represents a date (year, month, day (yyyy-MM-dd))

LocalTime Represents a time (hour, minute, second and milliseconds )

LocalDateTime Represents both a date and a time

Display Current Date

To display the current date, import the java.time.LocalDate class, and use its now() method:

Display Current Time


To display the current time (hour, minute, second, and milliseconds), import the
java.time.LocalTime class, and use its now() method:

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Example :

import java.time.*;

public class DateandTime {

public static void main(String[] args) {

LocalDate date=LocalDate.now();

System.out.println(date);

LocalTime time=LocalTime.now();

System.out.println(time);

OUTPUT :

2020-03-12

10:47:48.824

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Regular Expressions in Java
If we want to represent a Group of String object according to a particular pattern, then we
should go for Regular Expression.

Regular Expressions is an API for defining String patterns that can be used for searching,
manipulating a string in Java.
Email validation and passwords are few areas of strings where Regex are widely used to define
the constraints.
Regular Expressions are provided under java.util.regex package.
This consists of 3 classes and 1 interface.

The java.util.regex package provides following classes and interfaces for regular expressions.

1. MatchResult interface
2. Matcher class
3. Pattern class
4. PatternSyntaxException class

import java.util.regex.*;

class RegExDemo {

public static void main(String[] args){

int count=0;

Pattern p=Pattern.compile("ab");

Matcher m=p.matcher("ababbaba");

while(m.find())

count++;

System.out.println(m.start());

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


System.out.println("The Total number of Occurences : " + count);

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Serialization and Deserialization :
Serialization
The process of writing state of an object to a file is called serialization. But strictly speaking it is
the process of converting an object from java supported form to either file supported form or
network supported form.

By using FileOutputStream and ObjectOutputStream classes we can achieve Serialization.

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Deserialization
The process of Reading state of an object from a file is called Deserialization. But strictly
speaking it is the process of converting an object from either File or Network supported form
into java supported form.

By using FileInputStream and ObjectInputStream classes we can achieve.

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


JDBC :
- JDBC stands for java Java Database Connectivity.
- The JDBC API defines interfaces and classes or writing database application in java by
making database connection.

- 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.
There are four types of JDBC drivers:

o JDBC-ODBC Bridge Driver,


o Native Driver,
o Network Protocol Driver, and
o Thin Driver

- The java.sql package contains classes and interfaces for JDBC API.
- Following is the architectural diagram, which shows the location of the driver manager
with respect to the JDBC drivers and the Java application −

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


The JDBC API provides the following interfaces and classes −
 DriverManager: This class manages a list of database drivers.
 Driver: This interface handles the communications with the database server.
 Connection: This interface with all methods for contacting a database. The connection
object represents communication context, i.e., all communication with database is
through connection object only.
 Statement: You use objects created from this interface to submit the SQL statements to
the database.
 ResultSet: These objects hold data retrieved from a database after you execute an SQL
query using Statement objects.
 Closing Database connection

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).

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Basic JDBC Example:
Steps for connection

1. Loading Driver
2. Establishing connection
3. Preparing statement
4. Executing Statement
5. Getting Result
6. Closing Database connection

Loading Driver:

- A program can also explicitly loads JDBC drivers at any time.


- For example, the OracleDriver is loaded with the following statement

Class.forName(“Oracle.jdbc.driver.OracleDriver”);

Establishing Connection:

- When getConnection is called the DriverManager will attempt to locate a suitable driver
from amongst those loaded at initialization and those loaded explicitly.

DriverManager.getConnection (url, username, password)

url=”jdbc:oracle:thin:@localhost:1521:XE”

getConnection method return connection object on success otherwise null.

Closing Database Connection

- Connection object has a method called Close() to close the connection.

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Example:

import java.sql.*;
import java.util.*;
import java.io.*;
public class jdbcconnection {

public static void main(String[] args) throws Exception {

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"manager");
Statement st=con.createStatement();
String sql= "select * from student";
ResultSet rs=st.executeQuery(sql);
while(rs.next()) {
System.out.println(rs.getInt("id")+" "+rs.getString("name"));
}
con.close();
}

Output:

10 sandip
20 vikas

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


CRUD operation (insert, update, delete, and searching database)
basic database operations (CRUD - Create, Read, Update and Delete) using JDBC (Java Database
Connectivity) API. These CRUD operations are equivalent to the INSERT, SELECT, UPDATE and
DELETE statements in SQL language. Although the target database system is Oracle, but the
same technique can be applied for other database systems as well because the query syntax
used is standard SQL which is supported by all relational database systems.

Create a sample table with blank fields :


CREATE TABLE userid(
id varchar2(30) PRIMARY KEY,
pwd varchar2(30) NOT NULL,
fullname varchar2(50),
email varchar2(50)
);
Create JDBC java application using following command

1. Loading Driver
2. Establishing connection
3. Preparing statement
4. Executing Statement
5. Getting Result
6. Closing Database connection

 CREATE procedures : Performs the INSERT statement to create a new record.

CREATE TABLE Employee(


id varchar2(30) PRIMARY KEY,
name varchar2(30),
address varchar2(50),
designation varchar2(50)
);

 READ procedures : Reads the table records based on the primary keynoted within the input
parameter.

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


sql= "INSERT INTO Employee VALUES" +"(500, 'rajesh', 'Nanded', 'CEO')";

"SELECT * FROM Employee";

 UPDATE procedures : Executes an UPDATE statement on the table based on the specified
primary key for a record within the WHERE clause of the statement.

sql = "UPDATE Employee SET name='navin', " +


"address='Nanded' WHERE DISIGNATION='CEO'";

 DELETE procedures : Deletes a specified row in the WHERE clause.

sql = "DELETE FROM employee WHERE ID=500";

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


PreparedStatement :
- In JDBC three statement are their

1. Simple statement

2.Prepared Statement

3.Collable Statement

Simple Statement

- We can use simple statement to execute multiple queries.


Statement st=con.createStatement();

st.executeUpdate(“insert”);

st.executeUpdate(“delete”);

st.executeQuery(“select”);

i.e. if we want to execute multiple queries then we should go for simple Statement object. In
which each query will compile every time.

Per Query= Request time + Compile Time + Execution time + Response Time

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Prepared Statement

- if we want to work with only one query, but should be executed multiple times then we
should go for Prepared Statement.
- Used for execute single query for multiple time
- If we want to execute another query then we need to create new prepared object again.
- In prepared statement query will compile only once.

PreparedStatement pst=prepareStatement(sql query);

Pst.executeUpdate();

Pst.executeUpdate();

Pst.executeUpdate();

Per Query= Request time + Execution time + Response Time

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Establish the connection using jdbc :

import java.sql.*;
import java.util.*;
import java.io.*;
public class jdbcconnection {

public static void main(String[] args) throws Exception {

Class.forName("oracle.jdbc.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"manager");
Statement st=con.createStatement();
//String sql= "select * from student";
ResultSet rs=st.executeQuery("select * from stud");
while(rs.next()) {
System.out.println(rs.getInt("id")+"... "+rs.getString("name"));
}
con.close();
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Create table :
public class CreateTableExample {

static
{
//STEP 1 : Registering The Driver Class

try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch (ClassNotFoundException e)
{
System.out.println("Unable To Load The Driver class");
}
}

public static void main(String[] args)


{
Connection con = null;

Statement stmt = null;

try
{
//Database Credentials

String URL = "jdbc:oracle:thin:@localhost:1521:XE";

String username = "system";

String password = "manager";

//STEP 2 : Creating The Connection Object

con = DriverManager.getConnection(URL, username, password);

//STEP 3 : Creating The Statement Object

stmt = con.createStatement();

//Constructing The SQL Query

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


String sql = "CREATE TABLE collg(" +
"ID NUMBER NOT NULL, " +
"FIRST_NAME VARCHAR2(200), " +
"LAST_NAME VARCHAR2(200), " +
"DISIGNATION VARCHAR2(200))";

//Step 4 : Executing The Query

//We are using executeUpdate() method as we are executing CREATE statement

int i = stmt.executeUpdate(sql);

if(i == 0)
{
System.out.println("Table is created");
}
else
{
System.out.println("Table is not created");
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
//STEP 5 : Closing The DB Resources

//Closing the Statement object


try
{
if(stmt!=null)
{
stmt.close();
stmt=null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


//Closing the Connection object

try
{
if(con!=null)
{
con.close();
con=null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Insert operation
import java.sql.*;
public class InsertStatementExample {

static
{
//STEP 1 : Registering The Driver Class

try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch (ClassNotFoundException e)
{
System.out.println("Unable To Load The Driver class");
}
}

public static void main(String[] args)


{
Connection con = null;

Statement stmt = null;

try
{
//Database Credentials

String URL = "jdbc:oracle:thin:@localhost:1521:XE";

String username = "system";

String password = "manager";

//STEP 2 : Creating The Connection Object

con = DriverManager.getConnection(URL, username, password);

//STEP 3 : Creating The Statement Object

stmt = con.createStatement();

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


//Constructing The SQL Query

String sql = "INSERT INTO collg VALUES" +"(500, 'rajesh', 'Sharma', 'clerk')";

//Step 4 : Executing The Query

//We are using executeUpdate() method as we are executing INSERT statement

int i = stmt.executeUpdate(sql);

if(i != 0)
{
System.out.println("Row is created");
}
else
{
System.out.println("Row is not created");
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
//STEP 5 : Closing The DB Resources

//Closing the Statement object


try
{
if(stmt!=null)
{
stmt.close();
stmt=null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}

//Closing the Connection object

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


try
{
if(con!=null)
{
con.close();
con=null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Select Operation :

import java.sql.*;
public class SelectStatementExample {

static
{
//STEP 1 : Registering The Driver Class

try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch (ClassNotFoundException e)
{
System.out.println("Unable To Load The Driver class");
}
}

public static void main(String[] args)


{
Connection con = null;

Statement stmt = null;

ResultSet rs = null;

try
{
//Database Credentials

String URL = "jdbc:oracle:thin:@localhost:1521:XE";

String username = "system";

String password = "manager";

//STEP 2 : Creating The Connection Object

con = DriverManager.getConnection(URL, username, password);

//STEP 3 : Creating The Statement Object

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


stmt = con.createStatement();

//Constructing The SQL Query

String sql = "SELECT * FROM EMPLOYEE";

//Step 4 : Executing The Query

//We are using executeQuery() method as we are executing SELECT statement

rs = stmt.executeQuery(sql);

//Processing the ResultSet object

while (rs.next())
{
System.out.println("ID :"+rs.getInt(1));

System.out.println("First Name : "+rs.getString(2));

System.out.println("Last Name :"+rs.getString(3));

System.out.println("Designation :"+rs.getString(4));

System.out.println("-------------------");
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
//STEP 5 : Closing The DB Resources

//Closing the ResultSet object

try
{
if(rs!=null)
{
rs.close();
rs=null;

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


}
}
catch (SQLException e)
{
e.printStackTrace();
}

//Closing the Statement object

try
{
if(stmt!=null)
{
stmt.close();
stmt=null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}

//Closing the Connection object

try
{
if(con!=null)
{
con.close();
con=null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Update Operation :

import java.sql.*;
public class UpdateStatementExample {

static
{
//STEP 1 : Registering The Driver Class

try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch (ClassNotFoundException e)
{
System.out.println("Unable To Load The Driver class");
}
}

public static void main(String[] args)


{
Connection con = null;

Statement stmt = null;

try
{
//Database Credentials

String URL = "jdbc:oracle:thin:@localhost:1521:XE";

String username = "system";

String password = "manager";

//STEP 2 : Creating The Connection Object

con = DriverManager.getConnection(URL, username, password);

//STEP 3 : Creating The Statement Object

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


stmt = con.createStatement();

//Constructing The SQL Query

String sql = "UPDATE RGC SET FIRST_NAME='navin', " +


"LAST_NAME='verma' WHERE DISIGNATION='CEO'";

//Step 4 : Executing The Query

//We are using executeUpdate() method as we are executing UPDATE statement

int i = stmt.executeUpdate(sql);

if(i != 0)
{
System.out.println("Record is updated");
}
else
{
System.out.println("Record is not updated");
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
//STEP 5 : Closing The DB Resources

//Closing the Statement object

try
{
if(stmt!=null)
{
stmt.close();
stmt=null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


//Closing the Connection object

try
{
if(con!=null)
{
con.close();
con=null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Delete Operation :

import java.sql.*;
public class DeleteStatementExample {

static
{
//STEP 1 : Registering The Driver Class

try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch (ClassNotFoundException e)
{
System.out.println("Unable To Load The Driver class");
}
}

public static void main(String[] args)


{
Connection con = null;

Statement stmt = null;

try
{
//Database Credentials

String URL = "jdbc:oracle:thin:@localhost:1521:XE";

String username = "system";

String password = "manager";

//STEP 2 : Creating The Connection Object

con = DriverManager.getConnection(URL, username, password);

//STEP 3 : Creating The Statement Object

stmt = con.createStatement();

//Constructing The SQL Query

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


String sql = "DELETE FROM RGC WHERE ID=111";

//Step 4 : Executing The Query

//We are using executeUpdate() method as we are executing DELETE statement

int i = stmt.executeUpdate(sql);

if(i != 0)
{
System.out.println("Record is deleted");
}
else
{
System.out.println("Record is not deleted");
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
//STEP 5 : Closing The DB Resources

//Closing the Statement object

try
{
if(stmt!=null)
{
stmt.close();
stmt=null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


//Closing the Connection object

try
{
if(con!=null)
{
con.close();
con=null;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]

You might also like