0% found this document useful (0 votes)
53 views85 pages

Java Notes 7

Uploaded by

Abhishek
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
53 views85 pages

Java Notes 7

Uploaded by

Abhishek
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 85

Chapter 8

Java Input/Output and Networking


by Debasis Samanta

CONTENTS
• Introduction
• Java File I/O
o Java Files
o Input Stream
o Output Stream
• Networking in Java
o Internet addressing method in Java
o Communication using UDP
o Communication Using TCP
• Practice Questions

• Assignment

• Q&A

Introduction
Most Programs cannot accomplish their goals without accessing external data. This data is
retrieved from an input source. The results of a program are sent to an output destination. The
generic notion of an input source can abstract many different kinds of input : from a disk file, a
keyboard, or a network socket. Likewise, an output destination may be a disk file, on the screen,
or a network connection. These abstractions are a clean way to deal with input/output (I/O)
without having difference between the keyboard and network.
This Chapter is planned to discuss Java File I/O and Java Networking.

Java File I/O


Java provides java.io package which includes numerous class definitions and methods to
manipulate file and flow of data ( called I/O streams ). At the first level, java.io package consists
of four major classes : File, RandomAccessFile, InputStream, and
OutputStream. Subsequent sections are to discuss about the usefulness of these classes.

Java Files
There is a class named File in the package java.io which is useful to create a new file object, to
perform number of tests on file objects, and to perform number of file operations. Let us discuss
each of them with illustrations.
Creating a new File object :There are three constructors in the class File, and useful to create
(open) a file object; these constructors are illustrated as below :

File myFile;
myFile = new File (C:\ myDir \ myFile.Java" );

This constructor passes the information to create a file having name myFile.Java in the directory
myDir.
my File = new File(pathName, fileName);

Here, both arguments are of String types, and more useful if the directory or file name is passed
as a variable name.
File myDir = new File (pathToDir);
myFile = new File (myDir, fileName);

This constructor is useful when we have to open several files from a common directory.
In all the above cases, constructor returns a reference to a file object. If a file already exists then
it returns the reference of that file.
File handling Methods:There are number of methods to handle files. These are summarized
below :

Dealing with file names


String getName() - returns the name of the file object.
String getPath() - returns the path of the file object.
String getAbsolutePath() - returns the absolute path of a file when it is
not in the local machine.
String getParent() - returns the parent directory in which the file objec
t exist.
boolean renameTo(File newName) - returns true upon successful operation a
nd and false if one either attempts to rename a file so that it moves from one di
rectory to another or uses an already existing file name.
File test
boolean exists() - returns true if file exists else false.
boolean canWrite() - returns true if the file is writable else false.
boolean canRead() - returns true if the file is readable else false.
boolean isFile() - returns true if the object is a file object.
boolean isDirectory() - returns true if the object is a directory object.
boolean isAbsolute() - returns true if the file is within the system or i
t is relative.
General file information and utilities
long lastModified() - returns the date of the last modification in long f
ormat.
long length() - returns the length of the file in bytes.
boolean delete() - returns true if the file is successfully deleted. This
only operates on simple file object; even it cannot delete empty directory.
Directory utilities
boolean mkDir(File newDir)- This method creates a directory, returning tr
ue on success and false on failure; failure indicates that the path specified in t
he file object already exists, or that the directory cannot be created because the
path does not exist yet.
boolean mkDirs(File newDir) - This will return true after creating a dire
ctory where path of the directory may not exist. It not only creates a directory,
but will also create all the parents of the directory.
String[]list( ) - This method returns the list of all file names in a dir
ectory.

The following Illustration 8.1 is to illustrate the use of the few methods.

Illustration 8.1
/* Reading data from keyboard using DataInputStream class */

import java.io.*;

class Demonstration_121 {
public static void main(String args[ ] ) {
double principalAmount;
double rateOfInterest;
int numberOfYears;
try {
DataInputStream in = new DataInputStream(System.in);
String tempString;
System.out.print("Enter Principal Amount: ");
System.out.flush();
tempString = in.readLine();
principalAmount = Float.valueOf(tempString);
System.out.print("Enter Rate of Interest: ");

System.out.flush();
tempString = in.readLine();
rateOfInterest = Float.valueOf(tempString);
System.out.print("Enter Number of Years:");
System.out.flush();

tempString = in.readLine();
numberOfYears =Integer.parseInt(tempString);
}catch (Exception e){}
// Input is over: calculate the interest
int interestTotal =principalAmount*rateOfInterest*numberOfYears;
System.out.println("Total Interest = " + interestTotal);
}
}

Because class File does not let you read or write files, other classes will have to provide this
functionality. To read/write files, one can use one of the two approaches - using the class
RandomAccessFile, and using I/O stream classes, namely, InputStream and OutputStream. Out
of these two approaches, latter is more powerful. We will restrict ourselves into the last approach
only.

Input Stream
Input stream is a flow of data from an input source to the application under execution. Or in other
words, reading bytes of data from some kind of data source. Such a stream of inputs can be
managed by a number of methods which are defined in public abstract class InputStream which
is in java.io package. Here is a brief synopsis of the methods in InputStream :

int read( ) - returns an integer representation of the next available byt


e of input.
int read(byte b[ ] ) - attempts to read upto b.length bytes into b and r
eturns the actual number of bytes that were successfully read.
int read(byte b [ ], int off, int len) - attempts to read upto len byte
s into b starting at b[off],returning the number of bytes successfully read.
long skip(long n) - skips over n bytes of input returning the number of
bytes skipped.
int available( ) - returns the number of bytes of input currently availa
ble for available for reading.
void close( ) - close the input source; further read attempt on a closed
input will generate an IO Exception.
synchronized void mark(int read limit ) - places mark at the current poin
t in the input steam that will remain valid until readlimit bytes are read.
synchronized void reset()- returns the input pointer to the previously se
t mark.
boolean markSupported() - returns true if mark/reset supported on this st
ream.

All of the above methods in this class will throw an IOException on error condition.
From the class InputStream, number of classes inherited which are useful to define the process
of getting input from an input source. Here is a layout of the file input class hierarchy (Figure8.1).

Figure 8.1 :InputStream class hierarchy


We will just give a synopsis of each class and illustrate the use of FileInputStream class.
FileInputStream : The FileInputStream class uses actual data files as the basis for an
InputStream. An object of this class represents a text file which can be accessed in sequential
order, byte by byte. Also, you can choose to access one byte, several bytes, or the entire file.
Following is the Illustration 8.2 to show the input stream using FileInputStream.

/* Java FileInputStream : Reading a single character from a file */

import java.io.FileInputStream;

public class Demonstration_124 {


public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt"
); //create testout.txt
int i=fin.read();
System.out.print((char)i);

fin.close();
}catch(Exception e){System.out.println(e);}
}
}

It can be noted that a FileInputStream object can be opened either by any two of the following
ways :

FileInputStream = fin;
fin = new FileInputStream ( String name ); // The name inclu
des the input source file name.
or ,
File myFile ;
FileInputStream = fin;
myFile = new File (String name );
fin = new FileInputStream (myFile);

The other sub classes in the InputStream class are the same, only their constructor let you
specify a data source in variety of ways. For example, ByteArrayInputStream is an
implementation of an input stream that uses a byte array as the source. A string buffer input
stream is identical to a ByteArrayInputStream except that the internal buffer is a string instead of
a byte array. SequenceInputStream class supports the novel utility of concatenating multiple
input stream into a single one. There is FilteredStream class which extends the basic streams by
providing synchronization.

Illustration 8.3

/* Java FileInputStream : Reading a text from a file */

import java.io.FileInputStream;

public class Demonstration_125 {


public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:/Demonstration
/Demonstration-XII/testout.txt"); //create testout.txt
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}

Output Stream
Package java.io 's second main hierarchy branch consists of all stream classes concerned with
flow of data from program to output sources. The root for this hierarchy is called OutputStream
class. The output hierarchy is shown is figure 8.2.
In Java, output streams are even simpler than input streams; following methods are known in
order to handle output streams :

void write (int b) - writes out one byte at a time.


void write(byte b[ ] ) - writes out entire byte array i.e. a block of byt
es at a time.
void write (byte b[ ], int off, int len) - writes out len number of bytes
from the block of bytes b starting at offset off.
void flush ( ) - to flush the file buffer.
void close ( ) - close the out put stream; further write attempt on a clo
sed output stream will generate an IOException

Figure 8.2 :OutputStream hierarchy


The following discussion is to examine the FileOutputStream class only. Discussion of other
classes is beyond the scope of this Chapter.
The FileOutputStream objects are useful for writing out some text to a file. As with input files,
here also, you must open the file first, then you can write out your text. There are two
constructors analogous to the FileInputStream, which are used to open FileOutputStream objects
:
FileOutputStream fout ; // fout is the output stream obj
ect name
fout = new FileOutputStream (String name) // name is the output sou
rce file
Or,
File = myFile;
FileOutputStream fout;
myFile = new File(String name);
fout = new FileOutputStream (myFile);

Illustration 8.4

/* Java FileOutputStream : Write a byte into a file */

import java.io.FileOutputStream;

public class Demonstration_122a {


public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:/Demonstrat
ion/Demonstration-XII/test.txt");
fout.write(65);
fout.close();
System.out.println("File writing is over...");
}
catch(Exception e){
System.out.println(e);
}
}
}

Illustration 8.5

/* Java FileOutputStream : Write a byte into a file */


import java.io.*;

class Demonstration_122b {
public static void main(String args[]) {
byte cities[]={'D','E','L','H','I',' ','M','A','D','R','A','S','
','L','O','N','D','O', 'N','\n'};
FileOutputStream outfile=null; //create an output file stream
try {
outfile = new FileOutputStream("D:/Demonstration/Demonstr
ation-XII/city.txt");
// Connect the outfile stream to "city.txt"
outfile.write(cities); //Write data to the stream
outfile.close();
}
catch(IOException ioe) {
System.out.println(ioe);
System.exit(-1);
}
}
}

Illustration 8.6

/* Java FileOutputStream Write a string into a file */

import java.io.FileOutputStream;

public class Demonstration_123 {


public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:/Demonstrat
ion/Demonstration-XII/testout.txt");
String s="Welcome to NPTEL!";
byte b[]=s.getBytes();
//converting string into byte array
fout.write(b);
fout.close();
System.out.println("File writing is over...");
}catch(Exception e){
System.out.println(e);
}
}
}

Following is an illustration to use the FileInputStream and FileOutputStream to make a duplicate


of a given file.

Illustration 8.7

/* Using class File to check the file status */

import java.io.*;

class Demonstration_126 {
public static void getPaths (File f ) throws IOException {
System.out.println ("Name : " + f. getName( ) );
System.out.println ("Path : " + f. getPath ( ) );
System.out.println ("Parent : " + f.getParent ( ) );
}
public static void getInfo (File f ) throws IOException {
if (f.exists() ) {
System.out.print ("File exists ");
System.out.println (f.canRead( ) ? "and is readable" : ""
);
System.out.println ( f.canWrite( ) ? "and is writable" :
"");
System.out.println("File is last modified:" + f.lastModif
ied( ));
System.out.println("File is " + f.length( ) + "bytes" );
}
else
System.err.println (" File does not exist." );
}

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


File fileToCheck;
if (args.length > 0 ) {
for (int i = 0; i < args.length;i++ ) {
fileToCheck = new File(args[ i ]);
getPaths(fileToCheck);
getInfo(fileToCheck);
}
}
else
System.out.println (" Usage : Java file test ");
}
}

Illustration 8.8

/* Copying a file into another file using CharacterStream Class */

import java.io.*;
class Demonstration_127 {
public static void main (String args[]){
//Declare and create input and output files
File inFile = new File("D:/Demonstration/Demonstration-XII/input.
dat");
File outFile = new File("D:/Demonstration/Demonstration-XII/outpu
t.dat");
FileReader ins = null; // Creates file stream ins
FileWriter outs = null;
// Creates file stream outs
try {
ins = new FileReader (inFile);
// Opens inFile
outs = new FileWriter (outFile);
// Opens outFile
int ch; // Read and write till the end
while ((ch = ins.read()) != -1){
outs.write(ch) ;
}
} catch(IOException e) {
System.out.println(e);
System.exit(-1);
} finally{ //Close files
try {
ins.close();
outs.close();
}
catch (IOException e) { }
}
} // main
} // class

Illustration 8.9
/* Copying a file into another file using ByteStream Class */

import java.io.*;

class Demonstration_128{
public static void main (String args[]){
//Declare input and output file streams
FileInputStream infile = null ; //Input stream
FileOutputStream outfile = null ; //Output stream

byte byteRead; //Declare a variable to hold a byte

try {
//Connect infile to in.dat
infile = new FileInputStream("D:/Demonstration/Demonstrat
ion-XII/input.dat");
//Connect outfile to out.dat
outfile = new FileOutputStream("D:/Demonstration/Demonstr
ation-XII/out.dat");

//Reading bytes from in.dat and writing to out.dat


byteRead = (byte)infile.read();
while(byteRead != - 1){
outfile.write(byteRead);
byteRead = (byte)infile.read();
}
}
catch(FileNotFoundException e) {
System.out.println("File not found");
}
catch(IOException e) {
System.out.println(e.getMessage());
}
finally{ //Close files
try {
infile.close();
outfile.close();
}
catch(IOException e){}
}
}
}

Illustration 8.10

/* Example of BufferedOutputStream class for writing into a file */

import java.io.*;
public class Demonstration_129{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:/Demonstration/Demonstratio
n-XII/testout1.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to NPTEL!";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}

Illustration 8.11

/* Example of Java BufferedInputStream for reading from a file */

import java.io.*;

public class Demonstration_1210 {


public static void main(String args[]){
try{
FileInputStream fin = new FileInputStream("D:/De
monstration/Demonstration-XII/out.dat");
BufferedInputStream bin = new BufferedInputStrea
m(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}

Illustration 8.12

/* Java SequenceInputStream Example : Reading sequence of files */

import java.io.*;
class Demonstration_1211 {
public static void main(String args[])throws Exception{
FileInputStream input1=new FileInputStream("D:/Demonstration/Demo
nstration-XII/input1.txt");
FileInputStream input2=new FileInputStream("D:/Demonstration/Demo
nstration-XII/input2.txt");
SequenceInputStream inst=new SequenceInputStream(input1, input2);

int j;
while((j=inst.read())!=-1){
System.out.print((char)j);
}
inst.close();
input1.close();
input2.close();
}
}

Illustration 8.13

import java.io.*;

class Demonstration_1212{
public static void main (String args[]) throws IOException {
//Declare file streams
FileInputStream file1 = null;
FileInputStream file2 = null;
SequenceInputStream file3 = null; //Declare file3 to store combin
ed files

//Open the files to be concatenated


file1 = new FileInputStream("D:/Demonstration/Demonstration-XII/i
nput1.txt");
file2 = new FileInputStream("D:/Demonstration/Demonstration-XII/i
nput2.txt");

file3 = new SequenceInputStream(file1,file2) ; //Concatenate file


l and file2

//Create buffered input and output streams


BufferedInputStream inBuffer = new BufferedInputStream(fil
e3);
BufferedOutputStream outBuffer = new BufferedOutputStream(Sy
stem.out);

//Read and wri te till the end of buffers


int ch;
while((ch = inBuffer.read()) != -1)
outBuffer.write((char)ch);

inBuffer.close();
outBuffer.close();
file1.close();
file2.close();
}
}

Illustration 8.14
/* Handling a random access file */

import java.io.*;
class Demonstration_1213{
public static void main (String args[])
{
RandomAccessFile file = null;
try {
file = new RandomAccessFile("rand.dat","rw");

// Writing to the file


file.writeChar('X');
file.writeInt(555);
file.writeDouble(3.1412);

file.seek (0); // Go to the beginning

// Reading from the file


System.out.println(file.readChar());
System.out.println(file.readInt());
System.out.println(file.readDouble());

file.seek(2); // Go to the second item


System.out.println(file.readInt());

// Go to the end and append false to the file


file.seek(file.length());
file.writeBoolean(false);
file.seek(4) ;

System.out.println(file.readBoolean());
file.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Networking in Java
Java makes the networking easy and at the same time powerful. It provides java.net package
containing number of classes to support networking. Java supports Internet' s TCP/ IP Protocol.
Let us give a quick look about what do we mean Internet's TCP/IP. TCP/IP stands for
Transmission Control Protocol / Internet Protocol - the two data communication protocols. TCP
presents a connection-oriented service (like the telephone network. Here, we have to establish a
connection between two communicating processes and as soon as the connection is
established, data can be transferred. This protocol thus allows to send or receive arbitrary
amount of data without any boundaries. TCP guarantees delivery of data.
On the other hand, IP is a connection-less transport service. It is a datagram protocol which
means that data should be sent and received in individual packets. Each IP packet travels its
own, like an individual letter in a postal network; here thus, delivery is not guaranteed, packets
may be duplicated , lost, or arrive in a different order to that in which they were sent.
The other subtle difference between TCP and IP is that IP allows you to send a packet to an
individual machine on the Internet i.e. only single destination address is allowed; whereas, using
TCP, one can add more than one destination address.
Although, IP is not reliable but it is more efficient than TCP. There is one more TCP/IP protocol
which builds on IP to achieve its functionality : UDP (User Datagram Protocol). This came from
the fact that - IP is theoretically limited to sending a 64k byte packet, which would be insufficient
for sending many files or even many large GIF images embedded in web pages. One way to
solve this problem by breaking up the user's data stream into separate IP packets, numbering
them and then reassembling them on arrival. UDP is thus like a cross reference between IP and
TCP- it is a data gram protocol with the same 64k packet size limit of IP, but also allows port
addresses to be specified.
Java supports both the TCP and UDP protocol families.

Internet addressing method in Java


Java looks the whole Internet as a collection of host machines - each host is identified by a
number called port number. But Internet names are in the form of user readable strings like
"ds.nerist@ernet.in" instead of raw numbers. Java handle this situation nicely. In java.net
package there is InetAddress class that allows you to specify an address in a high level fashion
"host.subdomain.domain"; this class then converts this textual name into 32 bits binary string
form (for e.g. 259.161.69.192, (expressed in decimal)).
The InetAddress class has no visible constructors. In order to create an InetAddress object, you
have to use one of the available factory methods. Factory methods are simply static methods
that return an instance of the class they reside in. In this case, InetAddress has three such
methods - whose structures are stated below:

public static InetAddress getLocalHost ( );


public static InetAddress getByName (String host );
public static InetAddress [ ] getAllByName (String host );

The getLocalHost() method simply returns the InetAddress object that represents the local host
(i.e of your own machine). The getByName() method returns an InetAddress object for a host
name passed in. On the Internet, it is quite possible for a single name to be used to represent
several machines. The getAllByName() factory method returns an array of InetAddresses that a
particular name resolve to. These methods throw UnknownHostException in case of an error.
The InetAddress class also has a few non-static methods, which can be used on the objects
returned by the methods are mentioned below :
public string getHostName( ) - returns a string that represents the host
name associated with the InetAddress object.

public byte[ ] getAddress ( ) - returns a four elements byte array that r


epresents the object InetAddress in " Network byte order ".

public String toString ( ) - returns a string that lists the host name.

Communication using UDP


Java implements the low level communication with TCP/ IP UDP protocol using two classes
: DatagramPacket and DatagramSocket . The DatagramPacket object is the data container,
while the DatagramSocket is the mechanism used to send or receive the DatagramPackets.

DatagramPackets can be created using one of the two constructors as stated below
:
public DatagramPacket (byte ibuf [ ], int length);
public DatagramPacket (byte ibuf [ ], int length, InetAddress iaddr, int
iport);

The first constructor uses only a byte buffer and a length. It is used for receiving data over a
DatagramSocket. The second constructor adds target address and port number, which are used
by DatagramSocket to determine where the data in the packet will be sent.
There are several methods in this class DatagramPacket for accessing the internal state. They
can be called to get the destination address and port number of a packet, as well as the raw data
and its length. Following is a summary of each of them.

public InetAddress getAddress ( ) - returns the destination InetAddress.


It is typically used for sending.
public int getport ( ) - returns the integer destination port number. It
is typically used for sending.
public byte [ ] getData ( ) - returns the byte array of data contained in
the datagram. It is used to retrieve data from the datagram after it has been rece
ived.
public int getLength ( ) - returns the length of the valid data contained
in the byte array that would be returned from the getData() method.

As one can note that the there is no method in DatagramPacket class to send or receive any
data grams; this functionality is the responsibility of a companion class DatagramSocket. It has
following two constructors :
public DatagramSocket ( );
public DatagramSocket ( int port );

The first constructors is used to make communication between two ports in the local machine
whereas the second constructor is useful to do communication between two non-localized ports.
This class has the following methods :
public void send (DatagramPacket pkt) - takes a DatagramPacket object and
sends the datagram's data to the previously defined host and port address.
public synchronized void received (DatagramPacket pkt) - takes a Datagram
Packet object as a recipient for data gram to be received.
public synchronized void close( ) - to close the DatagramSocket that esta
blished when the communication is completed.

Following is an example to exercise the Data , Data gram Packet and Data gram socket classes.

Illustration 8.15 // Communication using UDP //

import java.net.*; // Include the java.net package


class CommnUDP {
public static int server port = 666; // A port 666 i
s decided as sever port
public static int client port = 999; // Another port
999 is decided as client port .
public static int size = 1024 ; // For the buffer limit
public static DatagramSocket ds; // Socket instance for
communication
public static byte buffer [ ] = new byte [size] ; // buff
er is to store a content
public static void theServer( ) {
int i =0;
while (true) // run till the end of
session
int c= System.in.read ( ); // read from ke
yboard
switch ( c) {
case -1 :
System.out.println (" Server quits : ");
return;

case '\n' : // Message entered for


transmission
ds.send (new DatagramPacket (buffer, i, Ine
tAddress.getLocalHost( ),clientPort ));
i = 0;
break;
default :
buffer [i++ ] = byte( c );
}
}
}
public static void theClient ( ) {
while(true) {
DatagramPacket pkt = new DatagramPacket
(buffer, buffer.length);
ds.receive (pkt) ;
System.out.println (new String (pkt.getD
ata ( ), 0, 0, pkt.getLength( ))));
}
}
public static void main (String args [ ] ) {
if (args.length == 1) {
ds = new DatagramSocket (serverPort );
theServer ( ); // send
ing message from server
} else {
ds = new DatagramSocket (clientPort );
theClient ( ); // Receiving me
ssage in client
}
}
}

This example illustrates the DatagramSocket constructor to perform the communication between
two ports on the local machine. To use this program, run Java commnUDP in one window; this
will be the client. Then run Java commnUDP abc; this will be the server. Anything that is typed in
the server window will be sent to the client window after a new line is entered.
Next Illustration 8.16 is to use UDP protocol to make a dialog between two distant machines in
the Internet

Illustration 8.16 // Communication using UDP outsi


de //
import java.net.*;
class DialogUDP {
public static int hostPort = 999; // Port No. of
the distant machine is assumed
public static void main (String args [ ] )
DatagramSocket ds;
DatagramPacket pkt;
InternetAddress hostAddress;
byte buffer [ ] = new byte [ 1024];
ds = new DatagramSocket ( ); // Establish a
socket in your machine
hostAddress = InetAddress getByName (" www.nerist.com" );
// If you are ready to send a message fo
r me.
// Phase I : To transmit a message
// Code for loading some message into buffer array
//
pkt = new DatagramPacket (buffer, buffer.length, hostAddr
ess, hostPort);
// Data gram packet for sending message
ds.send ( pkt) ; // message is transmitt
ed for the host machine.
// Phase II : To receive some message from host.
pkt = new DatagramPacket (buffer, buffer.length );
ds. receive (pkt); // data gram a
s a receiving packet
String message = new String (pkt.getData ( ), 0);
System.out.printin (" Message : " + message );
ds.close ( );
}
}

This program is a two phased dialogue. In the first phase a message from the user's machine will
be delivered to the host machine "www. nerist.com", and if the host send some message that will
be received in the second please.

Communication Using TCP


TCP communication based on the concept of Client/Server model. It allows bi-directional point-
to-point, stream based connection between two machines one of which is termed as sever and
other being the client. This is implemented using two core classes : Socket and ServerSocket.
These two classes are to establish socket connections between client and server. Sockets in
Java are end points of communication links between processes (which are under run in two
machines). The Socket class is to create a socket for client and the ServerSocket is for server.
Let us visit these two classes before proceeding further :

Socket class is having two constructor as below :

public Socket (String host , int port ) - creates a socket connecting the
local host to the named host and port.
public Socket (InetAddress address, int port) - creates a socket using p
re-exiting InetAddress object and a port.

The Socket class also contains methods to examine addresses and port information a
ssociated with it at any time.

public InetAddress getInetAddress( ) - returns the InetAddress associat


ed with the socket object .
public int get.port ( ) - returns the remote port with which socket objec
t is connected to.
public int getLocalPort () - returns the local port of the socket object
is connected to.

Once the Socket object is created, it then can gain access to the input and output
streams associated with it. Each of these next methods in Socket class are to do t
his :

public InputStream getInputStream( ) - returns the InputStream associate


with this socket.
public void close ( ) - close both the InputStream and OutputStream.

Similar to the Socket class, ServerSocket class is to create a socket connection f


or server. Two constructors are available here as :

public ServerSocket (int port ) - creates a ServerSocket on the specified


port.
public ServerSocket (int port, int count ) - creates a server socket on t
he specified port waiting "count" milliseconds if the port is in use.

It has the methods getInetAddress(), getLocalPort() and close() very similar to the method in
Socket class. Another extra method namely public Socket accept() is very important which
initiates communication for waiting clients and then returns with a normal socket.
The communication process is shown in Figure 8.3.
Figure 8.3 :Client-Server model for TCP communication
With this discussion, we can establish a TCP connection. Suppose, we want to write a server
system as SimpleServer. Using any one constructors in ServerSocket we can create a new
socket (listening ) on our machine that can accept incoming connections from clients across the
network. The port number we have to select between 0 - 65535 uniquely (0 -1023 is reserved for
standard Internet ports ). Suppose, we select a port number for our SimpleServer as 9876 (we
have chosen arbitrarily for testing purpose ). This is sufficient to create a new ServerSocket
object in our machine. Once a new ServerSocket object is created, it is then ready to listen on its
port form client requests to arrive. This can be initiated by invoking the accept ( ) method on the
SeverSocket object.
Following is the Illustration 8.17 to create a SimpleServer in our machine. This server will send
a message "Hello Net world!" whenever a client connects to it.

Illustration 8.17 // Minimal TCP/ IP Sever //

import java.net.*;
import java.io.*;
class SimpleServer {
public static void main (String args [ ] ) {
ServerSocket server;
Socket socket;
String msg = "Hello Net world !";
OutputStream oStream;
DataOutputStream dataOut;
try { // To create a ServerSocket obje
ct
Server = new ServerSocket (9876);
} catch (IOException e ) { }
// Run the Server to attend the clients for
ever
while (true) {
try {
socket = server.accept ( ); // Wait here an
d listen for a connection.
oStream = socket getOutputStream( ); //Get a com
munication stream for output
dataOut = new DataOutputStream(oStream); // Da
taStream out in binary
dataOut.writeUTF(mag); // Send messag
e to the client
dataOut.close ( ); // Close the Stream o
bject when message is transmitted
oStream.close ( ); // Close the ou
tput Stream or the current socket
socket.close ( ); // Close the cu
rrent socket connection
} catch (IOException e ) { }
} // listen for other clients if any
} // main ( )
} // Simple Server

Note : that this Application uses DataOutputStream to send message in binary bit string format
for portability only. The writeUTF(String) is a function defined in DataOutputStream class to write
a string object.
Following illustration 8.18 is the simple example for a client program.

Illustration 8.18 // Minimal TCP/IP client //

import java.net.*;
import java.io.*;
class SimpleClient {
public static void main (String args [ ] ) throws IOException
{
int c;
Socket socket;
InputStream iStream;
DataInputStream dataIn;
socket = new Socket ("New Server", 9876 );
// Create socket to connect the server "New Server" at port 9
876
iStream = socket getInput.Stream ( );
dataIn = new dataInputStream ( iStream); // Get
an input stream in binary
String mag = new String (dataIn.readUTF( ) ); // R
ead the string in Distream
System.out.println(mgg);
// When done just close the connection a
nd exit
dataIn.close ( );
iStream.close ( );
socket.close ( ); // Close the co
nnection
}
} // SimpleClient program

Practice Questions
Practice 8.1
import java.io.*;
class FileInOut{
public static void main (String args []) {
byte[] buffer = new byte [512] ; // A temp buffe
r to store text
int i = 0, size = 0;
FileOutputStream fout;
int c = 0;
try{
while (( c = System.in.read ( ) )!=-1 ) { // Read from
keyboard till ctrl+Z
buffer[i] = (byte) c;
i++;
}
size= i; // Number of bytes read
fout = new FileOutputStream (args[0]);
fout.write (buffer,0,size); // Write whole buffer i
nto the file
fout.close ( );
}
catch(IOException ee) {}
catch (ArrayIndexOutOfBoundsException e) { }
}
}

Practice 8.2
import java.io.*;
class InterestCalculator
{
public static void main(String args[ ] ) {
Float principalAmount = new Float(0);
Float rateOfInterest = new Float(0);
int numberOfYears = 0;

DataInputStream in = new DataInputStream(System.in);


String tempString;

try{
System.out.print("Enter Principal Amount: ");
System.out.flush();
tempString = in.readLine();
principalAmount = Float.valueOf(tempString);
System.out.print("Enter Rate of Interest: ");
System.out.flush();
tempString = in.readLine();
rateOfInterest = Float.valueOf(tempString);

System.out.print("Enter Number of Years: ");


System.out.flush();

tempString = in.readLine();
numberOfYears = Integer.parseInt(tempString);
}
catch(IOException e) {}
// Input is over: calculate the interest
float interestTotal = principalAmount*rateOfInterest*numberOf
Years*0.01f;

System.out.println("Total Interest = " + interestTotal);


}
}

Practice 8.3
import java.io.*;

class FileTest {
public static void main (String args [ ] ) throws IOException {
File fileToCheck;
if (args.length > 0 ) {
for (int i = 0; i < args.length; i++ ) {
fileToCheck = new File(args[ i ]);
getNames (fileToCheck );
getInfo(fileToCheck);
}
}
else
System.out.println ("Usage : Java file test ");
}
public static void getNames (File f ) throws IOException {
System.out.println ("Name : " + f. getName( ) );
System.out.println ("Path : " + f. getPath ( ) );
System.out.println ("Parent : " + f.getParent ( ) );
}

public static void getInfo (File f ) throws IOException {


if (f.exists() ) {
System.out.print ("File exists ");
System.out.println (f.canRead( ) ? "and is readable" : "");
System.out.println ( f.canWrite( ) ? "and is writable" : "");
System.out.println ("File is last modified : " + f.lastModified( ));
System.out.println ("File is " + f.length( ) + "bytes" );
}
else
System.err.println (" File does not exist." );
}
}

Practice 8.4
import java.io.*;

class InputStreamTest {
public static void main (String args [ ] ) {
int size;
// To open a file input stream.
FileInputStream fin;
try{
fin = new FileInputStream ("InputStreamTest.java");
size = fin.available( ); // returns the number o
f bytes available
System.out.println("Total bytes ::" + size);

System.out.println ( " First � is displayed : Using read


( )");
for (int i = 0; i < size /4 ; i++ ) {
System.out.println ((char) fin.read( ) );
}
System.out.println (" Remaining bytes :" + fin.available(
) );

System.out.println ("Next � is displayed : Using read( b


[ ] )");
byte b[] = new byte[size/4];
if (fin.read (b) != b.length )
System.err.println ("File reading error : ");
else {
String temp = new String (b, 0, 0, b.length );
// Convert the bytes into string
System.out.println (temp) ;
// display text string.

System.out.println ( " Still available : " + fin


.available( ) );
System.out.println ( " skipping � : Using skip
( )" );
fin.skip(size/4);
System.out.println (" File remaining for read ::
" + fin.available( ) );
}
fin.close ( );
// Close the input stream
}
catch(FileNotFoundException e1) { System.out.println ("Fi
le not found"); }
catch(IOException e) { System.out.println ("IO Exception"
); }
}
}

practice 8.5
//Copying characters from one file into another

import java.io.*;
class CopyCharacters
{
public static void main (String args[])
{
//Declare and create input and output files

File inFile = new File("input.txt");


File outFile = new File("output.txt");
FileReader ins = null; // Creates file stream ins
FileWriter outs = null; // Creates file stream outstry {
try{
ins = new FileReader (inFile) ; // Opens inFile
outs = new FileWriter (outFile) ; // Opens outFile
// Read and write till the end
int ch;

while ((ch = ins.read()) != -1)


{
outs.write(ch) ;
}
}
catch(IOException e) {
System.out.println(e);
System.exit(-1);
}
finally //Close files
{
try {
ins.close();
outs.close();
}
catch (IOException e) { System.out.println(e); }
}
} // main
} // class
practice 8.6
import java.io.*;

class WriteBytes {
public static void main(String args[]) {
//Declare and initialize a byte array
byte[] cities ={'D','E','L','H','I','\n','M','A','D','R',
'A','S','\n','L','O','N','D','O','N','\n'};
//create an output file stream
FileOutputStream outfile=null;
try{
// Connect the outfile stream to "city.txt"
outfile = new FileOutputStream("city.txt");
//Write data to the stream
outfile.write(cities);
outfile.close();
}
catch(IOException ioe) {
System.out.println(ioe);
System.exit(-1);
}
}
}
practice 8.7
import java.io.*;
class ReadBytes {
public static void main (String args[]) {
// Create an input file stream
FileInputStream infile = null;
int b;
try {
// Connect infile stream to the required file
infile = new FileInputStream(args[0]);
// Read and display data
while((b = infile.read()) != -1) {
System.out.print((char)b);
}
infile.close();
}
catch(IOException ioe) {
System.out.println(ioe);
}
}
}
practice 8.8
import java.io.*;
class CopyBytes
{
public static void main (String args[])
{
//Declare input and output file streams
FileInputStream infile = null; //Input stream
FileOutputStream outfile = null; //Output stream
//Declare a variable to hold a byte
byte byteRead;
try {
//Connect infile to input.txt
infile = new FileInputStream("input.txt");
//Connect outfile to output.txt
outfile = new FileOutputStream("output.txt");
//Reading bytes from input.txt and
//writing to output.txt
do{
byteRead = (byte) infile.read();
outfile.write(byteRead);
}
while(byteRead != -1);
}
catch(FileNotFoundException e) {
System.out.println("File not found");
}
catch(IOException e) {
System.out.println(e.getMessage());
}
finally //Close files
{
try {
infile.close();
outfile.close();
}
catch(IOException e){}
}
}
}

practice 8.9
import java.io.*;
class ReadWritePrimitive
{
public static void main (String args[]) throws IOException
{
File primitive = new File("prim.dat");
FileOutputStream fos = new FileOutputStream(primitive);
DataOutputStream dos = new DataOutputStream(fos);

//Write primitive data to the "prim.dat" file


dos.writeInt(1999);
dos.writeDouble(375.85);
dos.writeBoolean(false);
dos.writeChar('X');
dos.close();
fos.close();
//Read data from the "prim.dat" file
FileInputStream fis = new FileInputStream(primitive);
DataInputStream dis = new DataInputStream(fis);
System.out.println(dis.readInt());
System.out.println(dis.readDouble());
System.out.println(dis.readBoolean());
System.out.println(dis.readChar());
dis.close();
fis.close();
}
}
practice 8.10
import java.io.*;

class ReadWriteIntegers
{
public static void main (String args[])
{
//Declare data streams
DataInputStream dis = null; //Input stream
DataOutputStream dos = null; //Output stream
//Construct a file
File intFile = new File("rand.dat");
//Writing integers to rand.dat file
try
{
//Create output stream for intFile file
dos = new DataOutputStream(new FileOutputStream(
intFile));
for(int i=0;i<20;i++)
dos.writeInt ((int) (Math. random () *10
0));
}
catch(IOException ioe)
{
System.out.println(ioe.getMessage());
}
finally
{
try
{
dos.close();
}
catch(IOException ioe) { }
}
//Reading integers from rand.dat file
try {
//Create input stream for intFile file
dis = new DataInputStream(new FileInputStream(in
tFile));
for(int i=0;i<20;i++) {
int n = dis.readInt();
System.out.print(n + " ");
}
}
catch(IOException ioe) {
System.out.println(ioe.getMessage());
}
finally {
try {
dis.close();
}
catch(IOException ioe) { }
}
}
}
practice 8.11
import java.io.*;

class SequenceBuffer
{
public static void main (String args[]) throws IOException
{
//Declare file streams
FileInputStream file1 = null;
FileInputStream file2 = null;

//Declare file3 to store combined files


SequenceInputStream file3 = null;
//Open the files to be concatenated
file1 = new FileInputStream("input.txt");
file2 = new FileInputStream("output.txt");
//Concatenate file1 and file2 into file3
file3 = new SequenceInputStream(file1,file2) ;
//Create buffered input and output streams
BufferedInputStream inBuffer = new BufferedInputStream(fi
le3);
BufferedOutputStream outBuffer = new BufferedOutputStream
(System.out);
//Read and wri te till the end of buffers
int ch;
while((ch = inBuffer.read()) != -1)
outBuffer.write((char)ch);
inBuffer.close();
outBuffer.close();
file1.close();
file2.close();
}
}

practice 8.12
import java.io.*;
class RandomIO
{
public static void main (String args[])
{
RandomAccessFile file = null;
try
{
file = new RandomAccessFile("rand.txt","rw");
// Writing to the file
file.writeChar('X');
file.writeInt(555);
file.writeDouble(3.1412);
file.seek (0); // Go to the beginning // Reading
from the file
System.out.println(file.readChar());
System.out.println(file.readInt());
System.out.println(file.readDouble());
file.seek(2); // Go to the second item
System.out.println(file.readInt());
// Go to the end and append false to the file
file.seek(file.length());
file.writeBoolean(false);
file.seek (4) ;
System.out.println(file.readBoolean());
file.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}

practice 8.13
import java.io.*;
class RandomAccess
{
static public void main(String args[])
{
RandomAccessFile rFile;
try
{
rFile = new RandomAccessFile("city.txt","rw");

rFile.seek(rFile.length()); // Go to the end


rFile.writeBytes("MUMBAI\n"); //Append MUMBAI

rFile.close();
}
catch(IOException ioe)
{
System.out.println(ioe);
}
}
}

practice 8.14
import java. util. *; // For using StringTokenizer class
import java.io.*;
class Inventory
{
static DataInputStream din = new DataInputStream(System.in);
static StringTokenizer st;
public static void main (String args[]) throws IOException
{
DataOutputStream dos = new DataOutputStream(new FileOutpu
tStream("invent.txt"));
// Reading from console
System.out.println("Enter code number");
st = new StringTokenizer(din.readLine());
int code = Integer.parseInt(st.nextToken());
System.out.println("Enter number of items");
st = new StringTokenizer(din.readLine());
int items = Integer.parseInt(st.nextToken());
System.out.println("Enter cost");
st = new StringTokenizer(din.readLine());
double cost = new Double(st.nextToken()).doubleValue();
// Writing to the file "invent.txt"
dos.writeInt(code);
dos.writeInt(items);
dos.writeDouble(cost);
dos.close();
// Processing data from the file
DataInputStream dis = new DataInputStream(new FileInputSt
ream("invent.txt"));
int codeNumber = dis.readInt();
int totalItems = dis.readInt();
double itemCost = dis.readDouble();
double totalCost = totalItems * itemCost;
dis.close();
// Writing to console
System.out.println();
System.out.println("Code Number : " + codeNumber);
System.out.println("Item Cost : " + itemCost);
System.out.println("Total Items : " + totalItems);
System.out.println("Total Cost : " + totalCost);
}
}

practice 8.15
import java.io.*;
import java.awt.*;
import java.awt.event.*;
class StudentFile extends Frame implements ActionListener
{
// Defining window components
TextField number, name, marks;
Button enter, done;
Label numLabel, nameLabel, markLabel;
DataOutputStream dos;

// Initialize the Frame


public StudentFile()
{
super("Create Student File");
}
// Setup the window
public void setup()
{
resize(400, 200);
setLayout(new GridLayout(4,2));

// Create the components of the Frame


number = new TextField(25);
numLabel = new Label("Roll Number");
name = new TextField(25);
nameLabel = new Label ("Student Name");
marks = new TextField(25);
markLabel = new Label("Marks");
enter = new Button("ENTER");
done = new Button("DONE");
// Add the components to the Frame
add(numLabel);
add(number);
add(nameLabel);
add(name);
add(markLabel);
add(marks);
add(enter);
add(done);
enter.addActionListener(this);
done.addActionListener(this);
// Show the Frame
show();
// Open the file
try
{
dos = new DataOutputStream(new FileOutputStream("student.
txt"));
}
catch(IOException e)
{
System.err.println(e.toString());
System.exit(1);
}
}

// Write to the file


public void addRecord()
{
int num;
Double d;
num = (new Integer(number.getText())).intValue();
try
{
dos.writeInt(num);
dos.writeUTF(name.getText());
d = new Double(marks.getText());
dos.writeDouble(d.doubleValue());
}
catch(IOException e) { }
// Clear the text fields
number.setText(" ");
name.setText(" ");
marks.setText(" ");
}
// Adding the record and clearing the TextFields
public void cleanup()
{
if(!number.getText(). equals(" "))
{
addRecord();
}
try
{
dos.flush();
dos.close();
}
catch(IOException e) { }
}

// Processing the event

public void actionPerformed(ActionEvent e)


{
Button source = (Button)e.getSource();
if(source.getLabel() == "DONE"){
cleanup();
System.exit(0);

}
if(source.getLabel() == "ENTER")
{
addRecord();

// Execute the program


public static void main (String args[])
{
StudentFile student = new StudentFile();
student.setup();
}
}

practice 8.16
import java.io.*;
import java.awt.*;
import java.awt.event.*;

class ReadStudentFile extends Frame implements ActionListener


{
// Defining window components
TextField number, name, marks;
Button next, done;
Label numLabel, nameLabel, markLabel;
DataInputStream dis;
boolean moreRecords = true;
// Initialize the Frame
public ReadStudentFile()
{
super("Create Student File");
}
// Setup the window
public void setup()
{
resize(400,200);
setLayout(new GridLayout(4,2));
// Create the components of the Frame
number = new TextField(25);
numLabel = new Label ("Roll Number");
name = new TextField(25);
nameLabel = new Label ("Student Name");
marks = new TextField(25);
markLabel = new Label("Marks");
next = new Button("NEXT");
done = new Button("DONE");
// Add the components to the Frame
add(numLabel);
add(number);
add(nameLabel);
add(name);
add(markLabel);
add(marks);
add(next);
add(done);
next.addActionListener(this);
done.addActionListener(this);
// Show the Frame
show();
// Open the file
try
{
dis = new DataInputStream(new FileInputStream("s
tudent.txt"));
}
catch(IOException e)
{
System.err.println(e.toString());
System.exit(1);
}
}
// Read from the file
public void readRecord()
{
int n;
String s;
double d;

try
{
n = dis.readInt();
s = dis.readUTF();
d = dis.readDouble();
number.setText(String.valueOf(n));
name.setText(String.valueOf(s));
marks.setText(String.valueOf(d));
}
catch(EOFException e)
{
moreRecords = false;
}
catch(IOException ioe)
{
System.out.println("IO ErrorN");
System.exit(1);
}
}
// Closing the input file
public void cleanup()
{
try
{
dis.close();
}
catch(IOException e) { }
}
// Processing the event

public void actionPerformed(ActionEvent e)


{
Button source = (Button)e.getSource();
if(source.getLabel() == "DONE"){
cleanup();
System.exit(0);

}
if(source.getLabel() == "NEXT")
{
readRecord();

// Execute the program

public static void main (String args[])


{
ReadStudentFile student = new ReadStudentFile();
student.setup() ;
}
}

Practice Questions �(JDBC)


Instructions:

1. Download �mysql-connector-java-5.1.20-bin.jar� in your present directory


.
2. Change IP address of database server as instructed during lab.
3. Give table name same as your name for all occurrences.
4. Run your jdbc program as

java �cp .: mysql-connector-java-5.1.20-bin.jar < Name of program>

practice 8.17
// This program illustrates how to connect to �test� database.
import java.sql.*;

public class Connect


{
public static void main (String[] args)
{
Connection conn = null;

try
{
String userName = "guest";
String password = "guest";
String url = "jdbc:mysql://10.14.100.141/test
";
Class.forName ("com.mysql.jdbc.Driver").newIn
stance ();
conn = DriverManager.getConnection (url, user
Name, password);
System.out.println ("Database connection esta
blished");
}
catch (Exception e)
{
System.err.println ("Cannot connect to databa
se server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database
connection terminated");
}
catch (Exception e) { /* ignore close
errors */ }
}
}
}
}
practice 8.18
// This program illustrates how to create a table.

import java.sql.*;
import java.sql.ResultSet;
public class CreateTableJavaDataBase
{
public static void main (String[] args)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String TableName;

try
{
String userName = "guest";
String password = "guest";
String url = "jdbc:mysql://10.14.100.141/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection (url, userName, pass
word);

// System.out.println ("Database connection established");

stmt = conn.createStatement();

stmt.execute("show tables");
rs = stmt.getResultSet();

System.out.println("\n\n ------- Result Before Create Table --


-------\n");
while (rs.next()) {
TableName = rs.getString("Tables_in_test");
// change this field name
System.out.println("Table Name: = "+TableName+"\n");
} //end while

// Crate a table called JavaCourse.

stmt.execute("create table JavaCourse(Roll Integer primary key, N


ame
Varchar(30), Marks Integer not null, Grade Varchar(2))");
stmt.execute("show tables");
rs = stmt.getResultSet();

System.out.println("\n\n ------- Result After Create Table ------


---\n");
while (rs.next()) {
TableName = rs.getString("Tables_in_test"); // change th
is field name
System.out.println("Table Name: = "+TableName+"\n");
} //end while
}
catch (SQLException ex){
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode())
;
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server")
;
}
finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { } // ignore
rs = null;
}

if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { } // ignore
stmt = null;
}

if (conn != null) {
try {
conn.close ();
// System.out.println ("Database conne
ction terminated");
}
catch (Exception e) { /* ignore close er
rors */ }
}
}
}
}
practice 8.19
// This program illustrates how to insert a record in a table.

import java.sql.*;
import java.sql.ResultSet;

public class InsertJavaDataBase


{
public static void main (String[] args)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String NameString, RollString, MarksString, GradeStrin
g;

try
{
String userName = "guest";
String password = "guest";
String url = "jdbc:mysql://10.14.100.141/test
";
Class.forName ("com.mysql.jdbc.Driver").newIn
stance();
conn = DriverManager.getConnection (url, user
Name, password);

// System.out.println ("Database connection established


");

stmt = conn.createStatement();

stmt.execute("SELECT * FROM JavaCourse");


rs = stmt.getResultSet();

System.out.println("\n\n ------- Result Before Insert-


--------\n");
while (rs.next()) {
NameString = rs.getString("Name");
RollString = rs.getString("Roll");
MarksString = rs.getString("Marks");
GradeString = rs.getString("Grade");

System.out.println("Name: = "+NameStrin
g+"\t\t"+"Roll: =
"+RollString+"\t\t"+"Marks: = "+MarksSt
ring+"\t\t"+"Grade: =
"+GradeString+"\n");
} //end while

//Insert four rows into JavaCourse Table

stmt.execute("INSERT INTO JavaCourse values (01,'Debasish Kund


u', 75, 'A')");
stmt.execute("INSERT INTO JavaCourse values(02,'Saikat Das', 8
5, 'EX')");
stmt.execute("INSERT INTO JavaCourse values(03,'Sandeep Banerj
ee', 65, 'B')");
stmt.execute("INSERT INTO JavaCourse values(04,'Raju Chatterje
e', 78, 'A')");
stmt.execute("SELECT * FROM JavaCourse");
rs = stmt.getResultSet();

System.out.println("\n\n ------- Result After Insert----


-----\n");
while (rs.next()) {
NameString = rs.getString("Name");
RollString = rs.getString("Roll");
MarksString = rs.getString("Marks");
GradeString = rs.getString("Grade");

System.out.println("Name: = "+NameStrin
g+"\t\t"+"Roll: =
"+RollString+"\t\t"+"Marks: = "+MarksSt
ring+"\t\t"+"Grade: =
"+GradeString+"\n");
} //end while
}
catch (SQLException ex){
// handle any errors
System.out.println("SQLException: " + ex.getMessage())
;
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode()
);
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server
");
}
finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { } // ignore
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { } // ignore
stmt = null;
}
if (conn != null) {
try {
conn.close ();
// System.out.println ("Database conne
ction terminated");
}
catch (Exception e) { /* ignore close er
rors */ }
}
}
}
}
practice 8.20
// This program illustrates how to insert a record in a table with input
// taking from user.
import java.sql.*;
import java.sql.ResultSet;
import java.util.Scanner;

public class InsertJavaDataBase1


{
public static void main (String[] args)
{
Connection conn = null;
PreparedStatement pstmt = null;
Statement stmt = null;
ResultSet rs = null;
String Name, Grade, NameString, RollString, MarksStrin
g, GradeString;
int Roll;
int Marks;

try
{
String userName = "guest";
String password = "guest";
String url = "jdbc:mysql://10.14.100.141/test
";
Class.forName ("com.mysql.jdbc.Driver").newIn
stance();
conn = DriverManager.getConnection (url, user
Name, password);

// System.out.println ("Database connection esta


blished");

System.out.println("\n\n ------- Results before Insert


---------\n");

stmt = conn.createStatement();

stmt.execute("SELECT * FROM JavaCourse");


rs = stmt.getResultSet();
while (rs.next()) {
NameString = rs.getString("Name");
RollString = rs.getString("Roll");
MarksString = rs.getString("Marks");
GradeString = rs.getString("Grade");

System.out.println("Name: = "+NameStri
ng+"\t\t"+"Roll: =
"+RollString+"\t\t"+"Marks: = "+MarksS
tring+"\t\t"+"Grade: =
"+GradeString+"\n");
} //end while
System.out.println("\n\n ------- Input for the entries of table (JavaCour
se) \n");

Scanner in = new Scanner(System.in);

System.out.println("\n Enter Name: \t");


Name = in.nextLine();

System.out.println("\n Enter Grade: \t");


Grade = in.nextLine();

System.out.println("\n Enter Roll: \t");


Roll = in.nextInt();

System.out.println("\n Enter Marks: \t");


Marks = in.nextInt();

// Insert into database

String QryString = "INSERT INTO JavaCourse (Roll,Name,Marks,Grade) VALUES


(?,?,?,?)";

pstmt = conn.prepareStatement(QryString);

pstmt.setInt(1, Roll);
pstmt.setString(2, Name);
pstmt.setInt(3, Marks);
pstmt.setString(4, Grade);

pstmt.executeUpdate();

System.out.println("\n\n ------- Results after Insert ---------\n");

stmt.execute("SELECT * FROM JavaCourse");


rs = stmt.getResultSet();
while (rs.next()) {
NameString = rs.getString("Name");
RollString = rs.getString("Roll");
MarksString = rs.getString("Marks");
GradeString = rs.getString("Grade");

System.out.println("Name: = "+NameString+"\t\t"+"Roll: = "+RollString+"


\t\t"+"Marks:
= "+MarksString+"\t\t"+"Grade: = "+GradeString+"\n");
} //end while
}
catch (SQLException ex){
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed

if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { } // ignore
rs = null;
}

if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { } // ignore
stmt = null;
}

if (conn != null) {
try {
conn.close ();
// System.out.println ("Database conne
ction terminated");
}
catch (Exception e) { /* ignore close er
rors */ }
}
}

if (pstmt != null) {
try {
pstmt.close ();
// System.out.println ("Database conne
ction terminated");
}
catch (Exception e) { /* ignore close er
rors */ }
}
}

}
practice 8.21
// This program illustrates how to update a record in a table.

import java.sql.*;
import java.sql.ResultSet;

public class UpdateJavaDataBase


{
public static void main (String[] args)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String NameString, RollString, MarksString, GradeStrin
g;

try
{
String userName = "guest";
String password = "guest";
String url = "jdbc:mysql://10.14.100.141/test
";
Class.forName ("com.mysql.jdbc.Driver").newIn
stance();
conn = DriverManager.getConnection (url, user
Name, password);

// System.out.println ("Database connection establishe


d");

stmt = conn.createStatement();

stmt.execute("SELECT * FROM JavaCourse");


rs = stmt.getResultSet();

System.out.println("\n\n ------- Result Before


Update ---------\n");
while (rs.next()) {
NameString = rs.getString("Name");
RollString = rs.getString("Roll");
MarksString = rs.getString("Marks");
GradeString = rs.getString("Grade");

System.out.println("Name: = "+NameStrin
g+"\t\t"+"Roll: =
"+RollString+"\t\t"+"Marks: = "+MarksSt
ring+"\t\t"+"Grade: =
"+GradeString+"\n");
} //end while

// Update a row
stmt.execute("update JavaCourse set Marks=85, Gr
ade='Ex' where
Name='Debasish Kundu'");

stmt.execute("SELECT * FROM JavaCourse");


rs = stmt.getResultSet();

System.out.println("\n\n ------- Result After Update --


-------\n");
while (rs.next()) {
NameString = rs.getString("Name");
RollString = rs.getString("Roll");
MarksString = rs.getString("Marks");
GradeString = rs.getString("Grade");

System.out.println("Name: = "+NameStri
ng+"\t\t"+"Roll: =
"+RollString+"\t\t"+"Marks: = "+MarksS
tring+"\t\t"+"Grade: =
"+GradeString+"\n");
} //end while
}
catch (SQLException ex){
// handle any errors
System.out.println("SQLException: " + ex.getMes
sage());
System.out.println("SQLState: " + ex.getSQLStat
e());
System.out.println("VendorError: " + ex.getErro
rCode());
}
catch (Exception e)
{
System.err.println ("Cannot connect to databa
se server");
}
finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { } // ignore
rs = null;
}

if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { } // ignore
stmt = null;
}

if (conn != null) {
try {
conn.close ();
// System.out.println ("Database conne
ction terminated");
}
catch (Exception e) { /* ignore close er
rors */ }
}

}
}
}
practice 8.22
// This program illustrates how to process the data stored in a table.
import java.sql.*;
import java.sql.ResultSet;
public class ProcessJavaDataBase
{
public static void main (String[] args)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
int TotalMarks=0, Num_Student=0;
float Avg_Marks;
String NameString, RollString, MarksString, GradeString;

try
{
String userName = "guest";
String password = "guest";
String url = "jdbc:mysql://10.14.100.141/test";
Class.forName ("com.mysql.jdbc.Driver").newInst
ance();
conn = DriverManager.getConnection (url, userNa
me, password);

// System.out.println ("Database connection establishe


d");
// Compute avarage marks

stmt = conn.createStatement();

stmt.execute("SELECT * FROM JavaCourse");


rs = stmt.getResultSet();

System.out.println("\n\n ------- Results ---------\n");


while (rs.next()) {
NameString = rs.getString("Name");
RollString = rs.getString("Roll");
MarksString = rs.getString("Marks");
GradeString = rs.getString("Grade");
TotalMarks = TotalMarks + Integer.parse
Int(MarksString);

System.out.println("Name: = "+NameStrin
g+"\t\t"+"Roll: =
"+RollString+"\t\t"+"Marks: = "+MarksSt
ring+"\t\t"+"Grade: =
"+GradeString+"\n");
} //end while

rs.last();
Num_Student = rs.getRow();
Avg_Marks = TotalMarks / Num_Student;

System.out.println("\n\n ------- AVERAGE Marks = "+Avg_


Marks+"--------");
}
catch (SQLException ex){
// handle any errors
System.out.println("SQLException: " + ex.getMes
sage());
System.out.println("SQLState: " + ex.getSQLStat
e());
System.out.println("VendorError: " + ex.getErro
rCode());
}
catch (ArithmeticException e) {
System.out.println("Division by zero.");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server
");
}
finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { } // ignore
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { } // ignore
stmt = null;
}

if (conn != null) {
try {
conn.close ();
// System.out.println ("Database conne
ction terminated");
}
catch (Exception e) { /* ignore close er
rors */ }
}

}
}
}
practice 8.23
// This program illustrates how to delete records in a table.

import java.sql.*;
import java.sql.ResultSet;

public class DeleteJavaDataBase


{
public static void main (String[] args)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String NameString, RollString, MarksString, GradeStrin
g;

try
{
String userName = "guest";
String password = "guest";
String url = "jdbc:mysql://10.14.100.141/test
";
Class.forName ("com.mysql.jdbc.Driver").newIn
stance();
conn = DriverManager.getConnection (url, user
Name, password);

// System.out.println ("Database connection establishe


d");

stmt = conn.createStatement();

stmt.execute("SELECT * FROM JavaCourse");


rs = stmt.getResultSet();

System.out.println("\n\n ------- Result Before Delete


---------\n");
while (rs.next()) {
NameString = rs.getString("Name");
RollString = rs.getString("Roll");
MarksString = rs.getString("Marks");
GradeString = rs.getString("Grade");

System.out.println("Name: = "+NameString+"\t\
t"+"Roll: =
"+RollString+"\t\t"+"Marks: = "+MarksString+"
\t\t"+"Grade: =
"+GradeString+"\n");
} //end while

// delete all rows

stmt.execute("delete from JavaCourse");

stmt.execute("SELECT * FROM JavaCourse");


rs = stmt.getResultSet();
system.out.println("\n\n ------- Result After Delete -
--------\n");
while (rs.next()) {
NameString = rs.getString("Name");
RollString = rs.getString("Roll");
MarksString = rs.getString("Marks");
GradeString = rs.getString("Grade");

System.out.println("Name: = "+NameStri
ng+"\t\t"+"Roll: =
"+RollString+"\t\t"+"Marks: = "+MarksS
tring+"\t\t"+"Grade: =
"+GradeString+"\n");
} //end while

}
catch (SQLException ex){
// handle any errors
System.out.println("SQLException: " + ex.getMes
sage());
System.out.println("SQLState: " + ex.getSQLStat
e());
System.out.println("VendorError: " + ex.getErro
rCode());
}
catch (Exception e)
{
System.err.println ("Cannot connect to databa
se server");
}
finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { } // ignore
rs = null;
}

if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { } // ignore
stmt = null;
}

if (conn != null) {
try {
conn.close ();
// System.out.println ("Database conne
ction terminated");
}
catch (Exception e) { /* ignore close er
rors */ }
}
}
}
}

practice 8.24
// This program illustrates how to delete a table.

import java.sql.*;
import java.sql.ResultSet;

public class DeleteTableJavaDataBase


{
public static void main (String[] args)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String TableName;

try
{
String userName = "guest";
String password = "guest";
String url = "jdbc:mysql://10.14.100.141/test"
;
Class.forName ("com.mysql.jdbc.Driver").newIns
tance();
conn = DriverManager.getConnection (url, userN
ame, password);

// System.out.println ("Database connection esta


blished");

stmt = conn.createStatement();

stmt.execute("show tables");
rs = stmt.getResultSet();

System.out.println("\n\n ---- Result Before Delete Tabl


e ---------\n");
while (rs.next()) {
TableName = rs.getString("Tables_in_tes
t"); // change this field name
System.out.println("Table Name: = "+TableName+"
\n");
} //end while

// Crate a table called JavaCourse.

stmt.execute("drop table JavaCourse");

stmt.execute("show tables");
rs = stmt.getResultSet();

System.out.println("\n\n ------- Result After Delete Tab


le ---------\n");
while (rs.next()) {
TableName = rs.getString("Tables_in_tes
t"); // change this field name
System.out.println("Table Name: = "+TableName+"
\n");
} //end while
}
catch (SQLException ex){
// handle any errors
System.out.println("SQLException: " + ex.getMes
sage());
System.out.println("SQLState: " + ex.getSQLStat
e());
System.out.println("VendorError: " + ex.getErro
rCode());
}
catch (Exception e)
{
System.err.println ("Cannot connect to databa
se server");
}
finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { } // ignore
rs = null;
}

if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { } // ignore
stmt = null;
}
if (conn != null) {
try {
conn.close ();
// System.out.println ("Database conne
ction terminated");
}
catch (Exception e) { /* ignore close er
rors */ }
}
}
}
}

Practice 8.25
// This program illustrates communications using UDP.

/* To use this program, run �java commnUDP� in one window; this will be
the client. Then run �java commnUDP abc� in another window; this will be the ser
ver. Anything that is typed in the server window will be sent to the client window
after a new line is entered.*/

import java.net.*;
import java.io.*; // Include the java.net package
class CommnUDP {

public static int serverPort = 666; // A port 666 is decided as sever po


rt
public static int clientPort = 999; // Another port 999 is decided as cli
ent port .
public static int size = 1024 ; // For the buffer limit
public static DatagramSocket ds; // Socket instance for communica
tion
public static byte buffer [ ] = new byte [size] ; // buffer is to
store a content

public static void theServer( ) {


int i =0;
while(true) { // run till the end of session
try{

int c= System.in.read( ); // read from keyboard


switch (c) {
case -1:
System.out.println ("Server quits : ");
return;
case '\n' : // Message entered for
transmission
ds.send(new DatagramPacket(buffer, i, InetAddress.getLocalHost(
), clientPort ));
i = 0;
break;
default :
buffer [i++ ] = (byte) c;
}
}
catch(UnknownHostException ee){System.out.println("Host not found
"); }
catch(IOException e){System.out.println("IO error"); }
}
}
public static void theClient ( ) {
while(true) {
try{
DatagramPacket pkt = new DatagramPacket (buffer, buffer.l
ength);
ds.receive (pkt) ;
System.out.println(new String (pkt.getData(), 0, 0, pkt.g
etLength()));
}
catch(IOException e){System.out.println("IO error"); }
}
}
public static void main (String args [ ] ) {
try{
if (args.length == 1) {
ds = new DatagramSocket (serverPort );
theServer(); // sending message from server
} else {
ds = new DatagramSocket (clientPort );
theClient ( ); // Receiving message in
client
}
}
catch(SocketException eee){ System.out.println("Socket Er
ror"); }
}
}

Practice 8.26
// This program illustrates how server sends a message �Hello Net world!� to a c
lient using TCP/IP.
// TCP/IP Sever program //

import java.net.*;
import java.io.*;
class SimpleServer {
public static void main (String args [ ] ) {
ServerSocket server;
Socket socket;
String msg = "Hello Net world !";
OutputStream oStream;
DataOutputStream dataOut;
try { // To create a ServerSocket obje
ct
server = new ServerSocket (9876);
// Run the Server to attend the clients for ever
while (true) {
socket = server.accept ( ); // Wait here and listen
for a connection.
oStream = socket.getOutputStream( ); //Get a communicatio
n stream for output
dataOut = new DataOutputStream(oStream); // DataStream
out in binary
dataOut.writeUTF(msg); // Send message to the
client
dataOut.close(); // Close the Stream object when mess
age is transmitted
oStream.close ( ); // Close the output Str
eam or the current socket
socket.close ( ); // Close the current so
cket connection
}
}
catch(IOException e) { }
// listen for other clients if any
} // main ( )
} // Simple Server

// TCP/IP Client program //

import java.net.*;
import java.io.*;
class SimpleClient {
public static void main (String args [ ] ) throws IOException
{
int c;
Socket socket;
InputStream iStream;
DataInputStream dataIn;
socket = new Socket ("localhost", 9876 );
// Create socket to connect the server �New Ser
ver� at port 9876
iStream = socket.getInputStream();
dataIn = new DataInputStream (iStream); // Get an inp
ut stream in binary
String msg = new String (dataIn.readUTF( ) ); // Read t
he string in Distream
System.out.println(msg);
// When done just close the connection and exit
dataIn.close ( );
iStream.close ( );
socket.close ( ); // Close the connection
}
} // SimpleClient program

Practice 8.27
Following is an application that opens a connection to a Web server and adds two n
umbers from the server connection. This is treated as the Web server as iterative,
that is, the server processes one client�s request at a time.
// Client Side Program (Simple Web Client)//

import java.io.*;
import java.net.*;

public class SimpleWebClient {


static DataOutputStream outbound;
static DataInputStream inbound;
static InputStreamReader reader;
static BufferedReader br;
public static void main(String args[])
{
try
{
// Open a client socket connection
Socket clientSocket1 = new Socket("localhost", 2
000);
System.out.println("Client1: " + clientSocket1);
String choice="y";
reader = new InputStreamReader(System.in);
br = new java.io.BufferedReader(reader);

outbound = new DataOutputStream(


clientSocket1.getOutputStream() );

inbound = new DataInputStream(


clientSocket1.getInputStream() );

while(choice.equals("y"))
{
int num1, num2, result;

System.out.println("Enter first Number")


;
num1 = Integer.parseInt(br.readLine());

System.out.println("Enter second Number"


);
num2 = Integer.parseInt(br.readLine());

outbound.writeInt(num1);
outbound.writeInt(num2);
result = inbound.readInt();
System.out.println("Sum = " + result);

System.out.print("Want to add more (y/n)


: ");
choice=br.readLine();
}
// Clean up
outbound.close();
inbound.close();
clientSocket1.close();
}
catch (UnknownHostException uhe)
{
System.out.println("UnknownHostException: " + uh
e);
}

catch (IOException ioe)


{
System.err.println("IOException: " + ioe);
}
}
}
// Sever Side Program (Simple Web Sever)//

import java.io.*;
import java.net.*;
import java.lang.*;

class SimpleWebServer
{
public static void main(String args[])
{
ServerSocket serverSocket = null;
Socket clientSocket = null;
ServiceClient sock;
int connects = 0;
try
{
// Create the server socket
serverSocket = new ServerSocket(2000, 5);
System.out.println("server started");
while (connects < 5)
{

clientSocket = serverSocket.accept();
sock = new ServiceClient(clientSocket);
sock.start();
connects++;
}
System.out.println("Closing server");
serverSocket.close();
}

catch (IOException ioe)


{
System.out.println("Error in SimpleWebServer: "
+ ioe);
}

class ServiceClient extends Thread


{
Socket client;
DataInputStream inbound ;
DataOutputStream outbound ;

ServiceClient(Socket clnt)
{
client=clnt;
}

public void run()


{ inbound = null;
outbound = null;
try
{
// Acquire the streams for IO
inbound = new DataInputStream( client.getInputSt
ream());
outbound = new DataOutputStream( client.getOutpu
tStream());

int num1, num2,result;

while(true)
{
//Accept two numbers
num1 = inbound.readInt();
num2 = inbound.readInt();
result=num1+num2;

//Send the result to client


outbound.writeInt(result);
}

}
catch(Exception e)
{

// Clean up
System.out.println("Cleaning up connection: " +
client);
try
{
outbound.close();
inbound.close();
client.close();
}
catch(Exception r)
{
}

}
}

Practice 8.28
Following is an application for concurrent server.
/******************* Client-side code **********************/

import java.io.*;
import java.net.*;

/**
* An application that opens a connection to a Web server and adds two nu
mbers from the server connection.
*/

public class SimpleWebClient1 {


static DataOutputStream outbound;
static DataInputStream inbound;
static InputStreamReader reader;
static BufferedReader br;
public static void main(String args[])
{

try
{
// Open a client socket connection
Socket clientSocket1 = new Socket("localhost", 2
000);
System.out.println("Client1: " + clientSocket1);
String choice="y";
reader = new InputStreamReader(System.in);
br = new java.io.BufferedReader(reader);

outbound = new DataOutputStream(


clientSocket1.getOutputStream() );

inbound = new DataInputStream(


clientSocket1.getInputStream() );

while(choice.equals("y"))
{

int num1, num2, result;


System.out.println("Enter first Number");
num1 = Integer.parseInt(br.readLine());
System.out.println("Enter second Number");
num2 = Integer.parseInt(br.readLine());
outbound.writeInt(num1);
outbound.writeInt(num2);
result = inbound.readInt();
System.out.println("Sum = " + result);
System.out.print("Want to add more (y/n) : ");
choice=br.readLine();
}
// Clean up
outbound.close();
inbound.close();
clientSocket1.close();
}
catch (UnknownHostException uhe)
{
System.out.println("UnknownHostException: " + uh
e);
}
catch (IOException ioe)
{
System.err.println("IOException: " + ioe);
}
}
}

/******************* Server-side code **********************/

import java.io.*;
import java.net.*;
import java.lang.*;

class SimpleWebServer1
{
public static void main(String args[])
{
ServerSocket serverSocket = null;
Socket clientSocket = null;
ServiceClient sock;
int connects = 0;
try
{
// Create the server socket
serverSocket = new ServerSocket(2000, 5);
System.out.println("server started");
while (connects < 5)
{
clientSocket = serverSocket.accept();
sock = new ServiceClient(clientSocket);
sock.start();
connects++;
}
System.out.println("Closing server");
serverSocket.close();
}
catch (IOException ioe)
{
System.out.println("Error in SimpleWebServer: "
+ ioe);
}

class ServiceClient extends Thread


{
Socket client;
DataInputStream inbound ;
DataOutputStream outbound ;

ServiceClient(Socket clnt)
{
client=clnt;
}
public void run()
{
inbound = null;
outbound = null;
try
{
// Acquire the streams for IO
inbound = new DataInputStream( client.getInputS
tream());
outbound = new DataOutputStream( client.getOutp
utStream());

int num1, num2,result;

while(true)
{
// Accept two numbers
num1 = inbound.readInt();
num2 = inbound.readInt();
result=num1+num2;

//Send the result to client


outbound.writeInt(result);
}
}
catch(Exception e)
{
// Clean up
System.out.println("Cleaning up connecti
on: " + client);
try
{
outbound.close();
inbound.close();
client.close();
}
catch(Exception r)
{
}

}
}

Assignment
Q: Crate a swing application to take input from users, execute sql query, and
show the results.

Q&A
Q: What are the types of Streams and classes of the Streams?
A: There are two types of Streams and they are
Byte Streams: provide a convenient means for handling input and output of
bytes.
Character Streams: provide a convenient means for handling input and output
of characters.
Byte stream classes: are defined by using two abstract classes, namely
InputStream and OutputStream.
Character Streams classes: are defined by using two abstract classes, namely
Reader and Writer.
Q: What is serialization and deserialization?
A: Serialization is the process of writing the states of an object to byte stream.
Deserialization is the process of restoring these objects.
Q: What is object serialization?
A: Serializing an object involves encoding its state in a structured way within a
byte array.
Once an object is serialized, the byte array can be manipulated in various
ways; it can be written to a file, sent over a network using a socket based
connection or RMI, or persisted within a database as a BLOB.
The serialization process encodes enough information about the object type
within the byte stream, allowing the original object to be easily recreated upon
deserialization at a later point in time.
Q: How many methods in the externalizable interface?
A: There are two methods in the externalizable interface.
You have to implement these two methods in order to make your class
externalizable.
These two methods are read external() and write external().
Q: What class allows you to read objects directly from a stream?
A: The ObjectInputStream class supports the reading of objects from input
streams..
Q: What is a transient variable?
A: A transient variable is a variable that may not be serializable.
If you don't want some field to be serialized, you can mark the field transient or
static..
Q: What is the purpose of the file class?
A: The File class is used to create objects that provide access to the files and
directories of a local file system.
Q: What happens to the object references included in the object?
A: The serialization mechanism generates an object graph for serialization.
Thus it determines whether the included object references are serializable or
not, this is a recursive process.
Thus when an object is serialized, all the included objects are also serializable
along with the original object.
Q: What happens to the static fields of a class during serialization?
A: • There are three exceptions in which serialization does not necessarily read
and write to the stream.

• These are Serialization ignores static fields, because they are not part of any
particular state.

• Base class fields are only handled if the base class itself is serializable.

• Transient fields.
Q: How do you represent a URL in Java programming language?
A: The Java API provides the URL class which can be used to represent the URL
address. You can create the URL object if you have the URL address string.
The URL class provides getter methods to get the components of the URL
such as host name, port, path, query parameters etc.
String urlString = 'http://xyz.com';
URL url = new URL(urlString);

Q: What are the key steps in reading from a URL connection?


A: 1. Create the URL object

2. Create URLConnection object


3. Open connection to URL
4. Get input stream from connection
5. Read from input stream
6. Close input stream

Q: What are the key steps in writing to a URL connection?


A: 1. Create the URL object

2. Create URLConnection object


3. Open connection to URL
4. Get output stream from connection
5. Write to output stream
6. Close output stream.

Q: What is the difference between TCP and UDP protocols?


A: TCP is a protocol that provides a reliable, point-to-point communication
channel that client-server application use to communicate with each other. To
communicate over TCP, a client program and server program must first
establish a connection to each other through sockets at each end of the
communication channel. To communicate, the client and server reads from and
writes to the sockets bound to the connection.
Like TCP, UDP is protocol that provides a communication channel that client-
server applications use to communicate with each other. But unlike TCP, the
message content and arrival time of communication sent via UDP are not
guaranteed. In UDP messages are sent via datagrams, which are independent,
self-contained packets of data..
Q: How do you broadcast datagrams to multiple clients?
A: Using UDP protocol, a server can send or broadcast datagrams to multiple
clients. Java programming language provides java.net.MultigramSocket which
can be used to broadcast datagrams to multiple client programs.
Q: What is a network interface?
A: A network interface is the point of interconnection between a computer and a
private or public network. A network interface is generally a network interface
card (NIC). Network interfaces can either have a physical form or can be
implemented in software.
The Java networking API provides the java.net.NetworkInterface class which
represents both these types of interfaces..
Q: How do you get a list of IP addresses that are assigned to a network
interface?
A: You can get a list of IP addresses that are assigned to a network interface
using the NetworkInterface class. You can obtain this information from a
NetworkInterface instance by using one of two methods.
1. getInetAddresses() - returns an Enumeration of InetAddress.
2. getInterfaceAddresses() - returns a list of java.net.InterfaceAddress
instances. This method is used when you need more information about an
interface address beyond its IP address such as it subnet mask..
Q: What are the key interfaces and classes of the JDBC API?
A: JDBC API provides the following key interfaces and classes.
Driver - The interface that every driver class must implement.

Driver Manager - Loads and manages database drivers.

Connection- Creates connection to a specific database. Connection interface


provides methods for creating statements and managing connections and their
properties.

Statement - Used for executing a static SQL statement and returning the resu
lts.
ResultSet - Represents the database results after executing the SQL statemen
t.

SQLException - Base exception that provides information on a database access


error or other SQL errors.

Q: What are the key steps to connect to a database using JDBC API?
A: There are two key steps to connecting to a database using Java JDBC API
1. Load JDBC Driver - Every database that can be connected using JDBC API
must have a corresponding JDBC Driver class that implements java.sql.Driver
interface. Before you can make a connection to the database you must load
the driver. From JDBC 4.0 onwards any JDBC driver found in the classpath is
automatically loaded. Prior to JDBC 4.0 you have to load the driver specifically
using Class.forName(JDBC Driver).
2. Open database connection - After loading the driver, you can open a
connection to the database by calling getConnection() method on
DriverManager class and passing the database connection URL, user id and
password as arguments.

You might also like