Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Lab File
CS 20722(CS)
INDEX
S.No
1.
2.
3.
Page
No.
Date of
Exp.
Date of
Sub.
05/08/15
08/10/15
05/08/15
08/10/15
05/08/15
08/10/15
4.
05/08/15
08/01/15
5.
13
12/08/15
08/10/15
6.
16
12/08/15
08/10/15
7.
21
12/08/15
08/10/15
8.
24
23/09/15
08/10/15
9.
25
23/09/15
08/10/15
10.
29
23/09/15
08/10/15
Remarks
EXPERIMENT -1
AIM: Write a program which takes a text file as an input and generate the tokens using split method.
DESCRIPTION:
The java.lang.String.split(String regex, int limit) method splits this string around matches of the
given regular expression. The array returned by this method contains each substring of this string that is
terminated by another substring that matches the given expression or is terminated by the end of the string.
If the expression does not match any part of the input then the resulting array has just one element, namely
this string.
CODE:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args)
{
String st = null;
BufferedReader br;
try {
br = new BufferedReader(new FileReader("C:/nplab/Hello.txt"));
StringBuilder sb = new StringBuilder();
String ln = br.readLine();
while (ln != null) {
sb.append(ln);
sb.append(System.lineSeparator());
ln = br.readLine();
}
st= sb.toString();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(str);
System.out.println("Using String class");
String delims = " ";
String[] tokens1 = str.split(delims);
OUTPUT:
EXPERIMENT 2
AIM: Write a program to which takes a text file as an input and generate tokens using StringTokenizer class.
DESCRIPTION:
The java.util.StringTokenizer class allows to break a string into tokens. It is simple way to break
string. StringTokenizer(String str, String delim) constructor creates StringTokenizer with specified string and
delimeter.
boolean hasMoreElements(): Checks if there is more tokens available.
Object nextElement(): Returns the next token from the StringTokenizer object.
CODE:
package stringtokens;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args)
{
String st = null;
BufferedReader br;
try {
br = new BufferedReader(new FileReader("E:/nplab/Hello.txt"));
StringBuilder sb = new StringBuilder();
String ln = br.readLine();
while (line != null) {
sb.append(ln);
sb.append("\n");
ln = br.readLine();
}
st= sb.toString();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(str);
String delims = " ";
System.out.println("Using StringTokenizer class");
StringTokenizer st = new StringTokenizer(str, delims);
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}
}
}
OUTPUT:
EXPERIMENT-3
AIM: Write a program which takes a text file as an input and extract the numbers from it and calculate the
sum of these using Scanner class.
DESCRIPTION:
The Scanner class is a class in java.util, which allows the user to read values of various types.
It breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting
tokens may then be converted into values of different types using the various next methods. hasNext()
method returns true if this scanner has another token in its input. In this program nextInt() and
nextDouble() methods have been used to extract the numbers and then the addition is performed.
CODE:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Main
{
public static void main(String[] args) throws FileNotFoundException
{
File f=new File("E:/nplab/Hello.txt");
Scanner sc=new Scanner(f);
int i;
double d,sum=0;
while(sc.hasNext())
{
if(sc.hasNextInt())
{
sum+=sc.nextInt();
}
else if(sc.hasNextDouble())
{
sum+=sc.nextDouble();
}
else
{
String s=sc.next();}
}
System.out.println("Sum = "+sum);
}
}
OUTPUT:
EXPERIMENT 4
AIM: Write a program to count the number of tokens of different data types.
DESCRIPTION:
The java.util.Scanner class is a simple text scanner which can parse primitive types. A Scanner
breaks its input into tokens using a delimiter pattern, which by default matches whitespace. A scanning
operation may block waiting for input. A Scanner is not safe for multithreaded use without external
synchronization.
boolean hasNextBoolean()
This method returns true if the next token in this scanner's input can be interpreted as a boolean value using
a case insensitive pattern created from the string "true|false".
boolean hasNextInt()
This method returns true if the next token in this scanner's input can be interpreted as an int value in the
default radix using the nextInt() method.
boolean hasNextDouble()
This method returns true if the next token in this scanner's input can be interpreted as a double value using
the nextDouble() method.
String next()
This method finds and returns the next complete token from this scanner.
The HashMap class uses a hashtable to implement the Map interface. This allows the execution time
of basic operations, such as get( ) and put( ), to remain constant even for large sets.
CODE:
package scannercount;
import java.util.*;
public class Main {
public static void main(String[] args)
{
Scanner sc=new Scanner("1 2 3 this is NIT Raipur 1 2 3.5 4 4.5 true false");
HashMap<String,Integer> map=new HashMap<String,Integer>();
int i;
double d;
boolean b;
String str;
while(sc.hasNext())
{
if(sc.hasNextInt())
{
i=sc.nextInt();
if(map.get("int")==null)
map.put("int",1);
else
{ Integer in=new Integer(map.get("int"));
map.put("int",in+1);
}
}
else if(sc.hasNextDouble())
{
d=sc.nextDouble();
if(map.get("double")==null)
map.put("double",1);
else
{ Integer in=new Integer(map.get("double"));
map.put("double",in+1);
}
}
else if(sc.hasNextBoolean())
{
b=sc.nextBoolean();
if(map.get("bool")==null)
map.put("bool",1);
else
{ Integer in=new Integer(map.get("bool"));
map.put("bool",in+1);
}
}
else
{
str=sc.next();
if(map.get("string")==null)
map.put("string",1);
else
{ Integer in=new Integer(map.get("string"));
map.put("string",in+1);
}
}
}
System.out.println("Integer tokens = "+map.get("int")+" Double tokens =
"+map.get("double")+"
Boolean tokens = "+map.get("bool")+" String tokens =
"+map.get("string"));
}
}
OUTPUT:
EXPERIMENT-5
AIM: Write a program to implement TCP Socket Programming in Java.
DESCRIPTION:
The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a
mechanism for the server program to listen for clients and establish connections with them.The following
steps occur when establishing a TCP connection between two computers using sockets.
1. The server instantiates a ServerSocket object, denoting which port number communication is to occur on.
2. The server invokes the accept() method of the ServerSocket class. This method waits until a client
connects to the server on the given port.
3. After the server is waiting, a client instantiates a Socket object, specifying the server name and port
number to connect to.
4. The constructor of the Socket class attempts to connect the client to the specified server and port number.
If communication is established, the client now has a Socket object capable of communicating with the
server.
5.On the server side, the accept() method returns a reference to a new socket on the server that is connected
to the client's socket.
CODE:
1.Server.java
import java.io.*;
import java.net.*;
public class Server
{
private static Socket socket;
public static void main(String[] args)
{
OutputStream os;
try
{
ServerSocket serverSocket = new ServerSocket(6309);
System.out.println("Server Started and listening to the port 6309");
//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String num = br.readLine();
System.out.println("Message received from client is "+num);
//Multiplying the number by 2 and forming the return message
String retMsg;
try
{
int intNum = Integer.parseInt(num);
OUTPUT:
1.Server
2.Client
EXPERIMENT-6
AIM: Write a program to send file from server to client using TCP Socket programming.
DESCRIPTION:
The Java.io.BufferedReader class reads text from a character-input stream, buffering characters so as
to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the
default size may be used.Each read request made of a Reader causes a corresponding read request to be
made of the underlying character or byte stream.
Class Constuctors:
BufferedReader(Reader in)
BufferedReader(Reader in, intsz)
Methods
int read()-This method reads a single character.
int read(char[] cbuf, int off, intlen)-This method reads characters into a portion of an array.
String readLine()-This method reads a line of text
CODE:
1.FromServer.java
import java.io.*;
import java.net.*;
public class FromServer {
public final static int SOCKET_PORT = 9909;
public final static String FILE_TO_SEND = "C:\\Users\\nitr\\Desktop\\NP Lab\\file1.txt";
public static void main(String[] args) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket Server = null;
Socket socket = null;
try
{
Server = new ServerSocket(SOCKET_PORT);
while (true)
{
System.out.println("Waiting...");
try
{
socket = Server.accept();
System.out.println("Accepted connection : " + socket);
// send file
OUTPUT:
Server
Client
EXPERIMENT 7
AIM: Write a program to implement UDP Socket Programming in java.
DESCRIPTION:
The DatagramPacket and DatagramSocket classes in the java.net package implement system-independent
datagram communication using UDP.DatagramSocket, DatagramPacket, and MulticastSocket are used to
send and receive packets over network.An application can send and receive DatagramPackets through a
DatagramSocket. DatagramPackets can be broadcast to multiple recipients all listening to a MulticastSocket.
CODE:
1.UDPServer.java
package udpsocket;
import java.net.*;
import java.io.*;
public class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
2.UDPClient.java
package udpsocket;
import java.net.DatagramPacket;
import java.net.*;
import java.io.*;
UDPClient
EXPERIMENT 8
AIM: Write a program to implement RMI in Java.
DESCRIPTION: The Java Remote Method Invocation (Java RMI) is a Java API that performs the objectoriented equivalent of remote procedure calls (RPC), with support for direct transfer of serialized Java
classes and distributed garbage collection.
The original implementation depends on Java Virtual Machine (JVM) class representation
mechanisms and it thus only supports making calls from one JVM to another. The protocol underlying this
Java-only implementation is known as Java Remote Method Protocol (JRMP
CODE:
1.Adder Interface
import java.rmi.*;
public interface Adder extends Remote
{
public int add(int x,int y)throws RemoteException;
}
2.AdderRemote.java
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
public class AdderRemote extends UnicastRemoteObject implements Adder
{
AdderRemote() throws RemoteException
{
super();
}
public int add(int x,int y)
{
System.out.println("Adding the numbers ");
return x+y;
}
}
3.MyServer.java
import java.rmi.*;
import java.net.*;
import java.io.*;
public class MyServer
{
public static void main(String args[]) throws RemoteException, MalformedURLException,
NotBoundException
{
try
{
Adder stub=new AdderRemote();
Naming.rebind("rmi://localhost:5000/sonoo",stub);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
4.MyClient.java
import java.rmi.*;
import java.net.*;
import java.io.*;
import java.util.*;
public class MyClient
{
public static void main(String args[]) throws RemoteException, MalformedURLException,
NotBoundException, IOException
{
try
{
Scanner sc = new Scanner(System.in);
System.out.println("give the numbers you want to add");
int x = sc.nextInt();
int y = sc.nextInt();
Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
System.out.println("result =" + stub.add(x,y));
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
MyServer
MyClient
EXPERIMENT-9
AIM:Write a program to display System Variables.
DESCRIPTION:
Environment variables are a set of dynamic named values that can affect the way
running processes will behave on a computer.They are part of the environment in which a
process runs.
System.getenv(String name) method gets the value of the specified environment
variable. An environment variable is a system-dependent external named value.
Environment variables should be used when a global effect is desired, or when an
external system interface requires an environment variable (such as PATH).
DECLARATION
public static String getenv(String name)
Parameters:
name -This is the name of the environment variable.
Return Value:
This method returns the string value of the variable, or null if the variable is not defined
in the system environment.
CODE:
import java.util.Map;
public class envMap {
public static void main (String[] args) {
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s=%s%n",
envName,
env.get(envName));
}
}
}
OUTPUT:
EXPERIMENT 9
AIM: Write a program to implement URL programming in Java.
DESCRIPTION: URL stands for Uniform Resource Locator and represents a resource
on the World Wide Web, such as a Web page or FTP directory.
This section shows you how to write Java programs that communicate with a URL.
The java.net.URL class represents a URL and has complete set of methods to manipulate
URL in Java.
CODE:
// File Name : URLConnDemo.java
import java.net.*;
import java.io.*;
public class URLConnDemo
{
public static void main(String [] args)
{
try
{
URL url = new URL("http://www.amrood.com");
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection = null;
if(urlConnection instanceof HttpURLConnection)
{
connection = (HttpURLConnection) urlConnection;
}
else
{
System.out.println("Please enter an HTTP URL.");
return;
}
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String urlString = "";
String current;
while((current = in.readLine()) != null)
{
urlString += current;
}
System.out.println(urlString);
}catch(IOException e)
{
e.printStackTrace();
}
}
}
OUTPUT: