Java Notes 7
Java Notes 7
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 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 :
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 :
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).
import java.io.FileInputStream;
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
import java.io.FileInputStream;
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 :
Illustration 8.4
import java.io.FileOutputStream;
Illustration 8.5
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
import java.io.FileOutputStream;
Illustration 8.7
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." );
}
Illustration 8.8
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
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");
Illustration 8.10
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
import java.io.*;
Illustration 8.12
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
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");
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.
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 String toString ( ) - returns a string that lists the host name.
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.
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.
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
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.
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.
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 :
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.
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.
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;
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);
tempString = in.readLine();
numberOfYears = Integer.parseInt(tempString);
}
catch(IOException e) {}
// Input is over: calculate the interest
float interestTotal = principalAmount*rateOfInterest*numberOf
Years*0.01f;
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 ( ) );
}
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);
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
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);
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;
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.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;
}
if(source.getLabel() == "ENTER")
{
addRecord();
practice 8.16
import java.io.*;
import java.awt.*;
import java.awt.event.*;
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
}
if(source.getLabel() == "NEXT")
{
readRecord();
practice 8.17
// This program illustrates how to connect to �test� database.
import java.sql.*;
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);
stmt = conn.createStatement();
stmt.execute("show tables");
rs = stmt.getResultSet();
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;
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);
stmt = conn.createStatement();
System.out.println("Name: = "+NameStrin
g+"\t\t"+"Roll: =
"+RollString+"\t\t"+"Marks: = "+MarksSt
ring+"\t\t"+"Grade: =
"+GradeString+"\n");
} //end while
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;
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);
stmt = conn.createStatement();
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");
pstmt = conn.prepareStatement(QryString);
pstmt.setInt(1, Roll);
pstmt.setString(2, Name);
pstmt.setInt(3, Marks);
pstmt.setString(4, Grade);
pstmt.executeUpdate();
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;
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);
stmt = conn.createStatement();
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'");
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);
stmt = conn.createStatement();
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;
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;
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);
stmt = conn.createStatement();
System.out.println("Name: = "+NameString+"\t\
t"+"Roll: =
"+RollString+"\t\t"+"Marks: = "+MarksString+"
\t\t"+"Grade: =
"+GradeString+"\n");
} //end while
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;
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);
stmt = conn.createStatement();
stmt.execute("show tables");
rs = stmt.getResultSet();
stmt.execute("show tables");
rs = stmt.getResultSet();
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 {
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
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.*;
while(choice.equals("y"))
{
int num1, num2, result;
outbound.writeInt(num1);
outbound.writeInt(num2);
result = inbound.readInt();
System.out.println("Sum = " + result);
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();
}
ServiceClient(Socket clnt)
{
client=clnt;
}
while(true)
{
//Accept two numbers
num1 = inbound.readInt();
num2 = inbound.readInt();
result=num1+num2;
}
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.
*/
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);
while(choice.equals("y"))
{
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);
}
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());
while(true)
{
// Accept two numbers
num1 = inbound.readInt();
num2 = inbound.readInt();
result=num1+num2;
}
}
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);
Statement - Used for executing a static SQL statement and returning the resu
lts.
ResultSet - Represents the database results after executing the SQL statemen
t.
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.