Java Chapter 5
Java Chapter 5
LECTURE - 1
I/O Basics, Reading Console Input, Writing Console Output, Reading
and Writing Files
Java’s I/O system is quite large, containing many classes, interfaces, and methods. Java
programs perform I/O through streams. An I/O stream is an abstraction that either produces
or consumes information. A stream is linked to a physical device by the Java I/O system. All
streams behave in the same manner, even if the actual physical devices they are linked to
differ.
1
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations
2
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations
Example-
import [Link].*;
public class ReadBytesDemo {
public static void main(String args[]) throws IOException
3
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations
{
byte data[] = new byte[100];
[Link]("Enter Some Charaters : ");
[Link](data);
[Link]("You Entered : ");
for(int i=0;i<[Link];i++)
{
[Link]((char) data[i]);
}
}
}
Output-
Enter Some Charaters :
The quick brown fox jumps over the lazy dog.
You Entered : The quick brown fox jumps over the lazy dog.
Since PrintStream is an output stream derived from OutputStream, it also implements the
low-level method write( ) and it is possible to write to the console by using write( ).
PrintStream supplies two additional output methods: printf( ) and format( ). Both give us
detailed control over the precise format of data that we output.
Example-
public class WriteDemo {
public static void main(String args[])
{
int a;
a='A';
[Link](a);
[Link]('\n');
}
}
4
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations
Output-
A
We will not often use write( ) to perform console output (although it might be useful in some
situations), that’s why print( ) and println( ) are substantially easier to use.
Reading a File
A file is opened for input by creating a FileInputStream object.
Here, fileName specifies the name of the file we want to open. If the file does not exist, then
FileNotFoundException is thrown. FileNotFoundException is a subclass of IOException.
Example-
Java File - [Link]
import [Link];
import [Link];
import [Link];
5
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations
{
[Link]("Usage: ReadFileDemo File");
return;
}
try
{
fin = new FileInputStream(args[0]);
//fin = new FileInputStream("[Link]");
}
catch(FileNotFoundException exc)
{
[Link]("File not found");
return;
}
try
{
//read bytes until EOF is encountered
do
{
i = [Link](); //read from the file.
if(i != -1)
{
[Link]((char) i);
}
}while(i != -1);
}
catch(IOException exc)
{
[Link]("Error reading file.");
}
try
{
[Link](); //closing the file.
}
catch(IOException exc)
{
[Link]("Error closing file.");
}
}
}
Text File- [Link] (The file which we are reading with the java program)
The quick brown fox jumps over the lazy dog.
Output-
6
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations
Writing to a File
To open a file for output we need to create a FileOutputStream object as:
Once we are done with an output file, we must close it using close( ) as:
Example-
Java [Link]
import [Link];
import [Link];
import [Link];
if([Link] != 2)
{
[Link]("Usage: WritetoFileDemo from to");
return;
}
7
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations
//Copy a file
try
{
//Attempt to open the files.
fin = new FileInputStream(args[0]);
fout = new FileOutputStream(args[1]);
do
{
i = [Link](); //Read from a file
if(i != -1 )
{
[Link](i); //Write to Other File.
}
}while(i != -1);
}
catch(IOException exc)
{
[Link]("I/O Error: " + [Link]());
}
finally
{
try
{
if(fin != null)
{
[Link]();
}
}
catch(IOException exc)
{
[Link]("Error Closing Output File");
}
}
}
}
8
Notes By: - Sanjeev Khatri (Assoc. Professor)
LECTURE - 2
Applets: Applet Fundamentals, Applet Architecture
At the time of Java’s creation, one of its most exciting features was the applet. An applet is a
special kind of Java program that is designed to be transmitted over the Internet and
automatically executed inside a Java-compatible web browser. These are the programs that
you can embed in web pages to provide some intelligence like play sounds, play animations.
Applet Architecture
The database server is connected to the JDBC driver, which is connected to the applet. The
applet is also connected to a browser, which is connected to a web server that communicates
with the database.
Courtesy - [Link]
→Because of waning browser support for applets (and other factors), JDK 9 deprecated the
entire applet API and With the release of JDK 11, applet support has been removed.
LECTURE - 3
The HTML Applet Tag, Passing Parameters to Applets
Applets are embedded in HTML documents with the <APPLET> tag. It contains attributes that
identify the applet to be displayed and, optionally, give the web browser hints about how it
should be displayed. Attributes are name/value pairs that are interpreted by a web browser
or appletviewer. Applets have both an opening <APPLET> and a closing </APPLET> tag.
Sandwiched between these can be any number of <PARAM> tags that contain data to be
passed to the applet:
<APPLET attribute
attribute ... >
<PARAM parameter >
<PARAM parameter >
...
</APPLET>
The definition of the <APPLET> tag lists a fixed set of recognized attributes; specifying an
incorrect or nonexistent attribute should be considered an HTML error. Three attributes are
required in the <APPLET> tag. These are width, height and code or object.
Parameters
Parameters are analogous to command-line arguments; they provide a way to pass
information to an applet. Each <PARAM> tag contains a name and a value that are passed as
strings to the applet:
There is no fixed set of parameter names or values. it’s up to the applet to interpret the
parameter name/value pairs that are passed to it. Any number of parameters can be
specified, and the applet may choose to use or ignore them as it sees fit. The applet might
also consider parameters to be either optional or required, and act accordingly.
Example-
[Link]
import [Link].*;
import [Link].*;
/*
<applet code="apletdemo2" width=300 height=50>
</applet>
*/
public class apletdemo2 extends Applet
{
String msg;
// set the foreground and background colors.
public void init()
{
setBackground([Link]);
setForeground([Link]);
msg = "Inside init( ) --";
}
// Initialize the string to be displayed.
public void start()
{
msg += " Inside start( ) --";
}
// Display msg in applet window.
public void paint(Graphics g)
{
msg += " Inside paint( ).";
[Link](msg, 10, 30);
}
}
[Link]
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code = "[Link]" width = "320" height = "120">
If your browser was Java-enabled, a "Applet Demo"
message would appear here.
</applet>
<hr>
</html>
1
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations
Output-
2
Notes By: - Sanjeev Khatri (Assoc. Professor)
LECTURE - 4
Networking Basics, Java and the Net
One of the most important reasons that Java became the premier language for network
programming are the classes defined in the [Link] package.
Networking Basics
➢ At the core of Java’s networking support is the concept of a socket. A socket identifies
an endpoint in a network. Sockets are at the foundation of modern networking
because a socket allows a single computer to serve many different clients at once, as
well as to serve many different types of information. This is accomplished through the
use of a port, which is a numbered socket on a particular machine.
➢ A server process is said to "listen" to a port until a client connects to it. A server is
allowed to accept multiple clients connected to the same port number, although each
session is unique. To manage multiple client connections, a server process must be
multithreaded or have some other means of multiplexing the simultaneous I/O.
➢ Socket communication takes place via a protocol. Internet Protocol (IP) is a low-level
routing protocol that breaks data into small packets and sends them to an address
across a network, which does not guarantee to deliver said packets to the destination.
➢ Transmission Control Protocol (TCP) is a higher-level protocol that manages to
robustly string together these packets, sorting and retransmitting them as necessary
to reliably transmit data. A third protocol, User Datagram Protocol (UDP), sits next to
TCP and can be used directly to support fast, connectionless, unreliable transport of
packets.
➢ Hypertext Transfer Protocol (HTTP) is the protocol that web browsers and servers use
to transfer hypertext pages and images. It is a quite simple protocol for a basic page-
browsing web server. When a client requests a file from an HTTP server, an action
known as a hit, it simply sends the name of the file in a special format to a predefined
port and reads back the contents of the file.
➢ A key component of the Internet is the address (IP Address). Every computer on the
Internet has one address. An Internet address is a number that uniquely identifies
each computer on the Net. Originally, all Internet addresses consisted of 32-bit values,
organized as four 8-bit values which was specified by IPv4. IPv6 uses a 128-bit value
to represent an address.
➢ As the numbers of an IP address describe a network hierarchy, the name of an Internet
address, called its domain name, describes a machine’s location in a name space.
➢ An Internet domain name is mapped to an IP address by the Domain Naming Service
(DNS).
Unit-5 [Link]. – AI&DS-IV I/O Operations
InetAddress
The InetAddress class is used to encapsulate both the numerical IP address and the domain
name for that address. We interact with this class by using the name of an IP host, which is
more convenient and understandable than its IP address.
Factory Methods
The InetAddress class has no visible constructors. To create an InetAddress object, we have
to use one of the available factory methods. Factory methods are merely a convention
whereby static methods in a class return an instance of that class.
1
Notes By: - Sanjeev Khatri (Assoc. Professor)
LECTURE - 5
TCP/IP Client Sockets URL, URL Connection, TCP/IP Server Sockets
Example –
The following example showing how to use Socket and ServerSocket Class to make
connection between client and server.
[Link](Using ServerSocket)
import [Link].*;
import [Link].*;
String str=(String)[Link]();
[Link]("message= "+str);
[Link]();
}
catch(Exception e)
{
[Link](e);
}
}
}
ClientExp(Using Socket)
import [Link].*;
import [Link].*;
[Link]("Hello Server");
[Link]();
[Link]();
[Link]();
}catch(Exception e)
{
[Link](e);
}
}
}
1
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations
URL
The URL provides a reasonably intelligible form to uniquely identify or address information
on the Internet. URLs are ubiquitous. Every browser uses them to identify information on the
Web. Within Java’s network class library, the URL class provides a simple, concise API to
access information across the Internet using URLs. All URLs share the same basic format,
although some variation is allowed.
Example-
import [Link];
import [Link];
2
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations
Output-
Protocol: https
Port: -1 → port is –1. This means that a port was not explicitly set.
Host: [Link]
File: /WhatsNew
URLConnection
URLConnection is a general-purpose class for accessing the attributes of a remote resource.
Once we make a connection to a remote server, we can use URLConnection to inspect the
properties of the remote object before actually transporting it locally. These attributes are
exposed by the HTTP protocol specification and, as such, only make sense for URL objects
that are using the HTTP protocol. URLConnection defines several methods.
Example-
import [Link];
import [Link];
import [Link];
import [Link];
long d = [Link]();
if(d==0)
{
[Link]("No date information.");
}
else
{
[Link]("Date: " + new Date(d));
}
d = [Link]();
if(d==0)
{
[Link]("No expiration information.");
}
3
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations
else
{
[Link]("Expires: " + new Date(d));
}
d = [Link]();
if(d==0)
{
[Link]("No last-modified information.");
}
else
{
[Link]("Last-Modified: " + new Date(d));
}
if(len == -1)
{
[Link]("Content length unavailable.");
}
else
{
[Link]("Content-Length: " + len);
}
if(len != 0)
{
[Link]("=== Content ===");
InputStream input = [Link]();
while(((c = [Link]()) != -1))
{
[Link]((char) c);
}
[Link]();
}
else
{
[Link]("No content available.");
}
}
}
This program establishes an HTTP connection to [Link] over port 80. It then
displays several header values and retrieves the content.
4
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations
HttpURLConnection
Java provides a subclass of URLConnection that provides support for HTTP connections. This
class is called HttpURLConnection. We obtain an HttpURLConnection in the same way just
shown, by calling openConnection() on a URL object, but we must cast the result to
HttpURLConnection. Once we have obtained a reference to an HttpURLConnection object,
we can use any of the methods inherited from URLConnection. We can also use any of the
several methods defined by HttpURLConnection.
Cookies
The [Link] package includes classes and interfaces that help manage cookies and can be
used to create a stateful (as opposed to stateless) HTTP session. The classes are
CookieHandler, CookieManager, and HttpCookie. The interfaces are CookiePolicy and
CookieStore.
5
Notes By: - Sanjeev Khatri (Assoc. Professor)
LECTURE - 6
Database Connectivity
A database is an organized collection of data. There are many different strategies for
organizing data to facilitate easy access and manipulation. A database management system
(DBMS) provides mechanisms for storing, organizing, retrieving and modifying data for many
users. Database Management Systems allow for the access and storage of data without
concern for the internal representation of data. Java programs communicate with databases
and manipulate their data using the Java Database Connectivity (JDBC) API.
JDBC is a standard Java API for database-independent connectivity between the Java
programming language and a wide range of databases. The JDBC library includes APIs for
each of the tasks commonly associated with database usage:
❖ Making a connection to a database
❖ Creating SQL or MySQL statements
❖ Executing SQL or MySQL queries in the database
❖ Viewing & Modifying the resulting records
JDBC is a specification that provides a complete set of interfaces that allows for portable
access to an underlying database. Java can be used to write different types of executables,
like - Java Applications, Java Applets, Java Servlets, Java ServerPages (JSPs), Enterprise
JavaBeans (EJBs). JDBC provides the same capabilities as ODBC, allowing Java programs to
contain database-independent code.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access
but in general JDBC Architecture consists of two layers:
❖ JDBC API: This provides the application-to-JDBC Manager connection.
❖ JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source.
The driver manager is capable of supporting multiple concurrent drivers connected to
multiple heterogeneous databases.
Unit-5 [Link]. – AI&DS-IV I/O Operations
DriverManager : This class manages a list of database drivers. Matches connection requests
from the java application with the proper database driver by using communication
subprotocol. The first driver that recognizes a certain subprotocol under JDBC will be used to
establish a database Connection.
Driver : This interface handles the communications with the database server. We will interact
directly with Driver objects very rarely. Instead, we use DriverManager objects, which
manages objects of this type. It also abstracts the details associated with working with Driver
objects.
Statement : We use objects created from this interface to submit the SQL statements to the
database. Some derived interfaces accept parameters in addition to executing stored
procedures.
ResultSet : These objects hold data retrieved from a database after you execute an SQL query
using Statement objects. It acts as an iterator to allow you to move through its data.
SQLException : This class handles any errors that occur in a database application.
1
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations
Relational Databases
Most popular database systems are relational databases. A relational database is a logical
representation of data that allows the data to be accessed without consideration of its
physical structure. A relational database stores data in tables. Tables are composed of rows,
and rows are composed of columns in which values are stored. One column of each row can
be the table’s primary key – a column (or group of columns) with a unique value that cannot
be duplicated in other rows. This guarantees that each row can be identified by its primary
key.
Basic SELECT Query - A SQL query “selects” rows and columns from one or more tables in a
database. The basic form of a SELECT query is-
WHERE Clause - It’s necessary to locate rows in a database that satisfy certain selection
criteria. Only rows that satisfy the selection criteria (formally called predicates) are selected.
SQL uses the optional WHERE clause in a query to specify the selection criteria for the query.
The basic form of a query with selection criteria is-
2
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations
ORDER BY Clause - The rows in the result of a query can be sorted into ascending or
descending order by using the optional ORDER BY clause. The basic formof a query with an
ORDER BY clause is-
Merging Data from Multiple Tables: INNER JOIN - It’s necessary to merge data from multiple
tables into a single result. Referred to as joining the tables, this is specified by an INNER JOIN
operator, which merges rows from two tables by matching values in columns that are
common to the tables. The basic form of an INNER JOIN is-
INSERT Statement - The INSERT statement inserts a row into a table. The basic form of this
statement is-
UPDATE Statement - An UPDATE statement modifies data in a table. Its basic form is-
UPDATE tableName
SET columnName1 = value1, columnName2 = value2, …, columnNameN = valueN
WHERE criteria
➢ Register the JDBC driver . Requires that we initialize a driver so we can open a
communications channel with the database.
3
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations
➢ Execute a query . Requires using an object of type Statement for building and
submitting an SQL statement to the database.
➢ Extract data from result set . Requires that we use the appropriate [Link]()
method to retrieve the data from the result set.
➢ Clean up the environment . Requires explicitly closing all database resources versus
relying on the JVM's garbage collection.
Example-
//Setp 1 - Import required packages
import [Link].*;
class mysqlcon
{
public static void main(String args[])
{
try
{
//Step 2 - Register JDBC driver
[Link]("[Link]");
4
Notes By: - Sanjeev Khatri (Assoc. Professor)
Unit-5 [Link]. – AI&DS-IV I/O Operations
catch(Exception e)
{
//Exception Handling
[Link]("Error" + [Link]());
}
}
}
The above example extracting data from a mysql database stdmarks and executing a query
which retrive data of those students having marks greater than 60.
[Link]("[Link]");
Connection con =
[Link]("jdbc:mysql://localhost:3306/stdmarks", "root",
"root");
//Statement stat = [Link]();
String sql = "insert into stddata (stdname, stdage, stdm1, stdm2,
stdm3, totmarks, perc, results) values('bcd',18,74,66,80,216,73.33,'First')";
PreparedStatement pst = [Link](sql);
int numRowsChanged = [Link](sql);
[Link](numRowsChanged);
//ResultSet rs = [Link]("insert into stdmarks (stdname,
stdage, stdm1, stdm2, stdm3, totmarks, perc, results)
values(‘abc’,18,70,66,80,216,72.0,’First’)");
[Link]();
}
catch(Exception e)
{
[Link]("Error" + [Link]());
}
}
}
5
Notes By: - Sanjeev Khatri (Assoc. Professor)