Anda di halaman 1dari 18

Assignment

On
Java

Topics:
1. Inet address
2. Factory method
3. URL connection
4. File handling

Submitted to:
submitted by:
Mr. Prakash
Ankit Kumar
089
MCA(4th
sem)

1. InetAddress
The InetAddress class has no visible constructors. To create an
InetAddress object, you have to use one of the available factory
methods. Factory methods are merely a convention whereby
static methods in a class return an instance of that class. This is
done in lieu of overloading a constructor with various parameter
lists when having unique method names makes the results much
clearer. In the case of InetAddress, the three methods
getLocalHost(), getByName(), and getAllByName() can be used to
create instances of InetAddress. These methods are shown here:

static InetAddress getLocalHost( )

throws UnknownHostException

static InetAddress getByName(String hostName)

throws UnknownHostException

static InetAddress[ ] getAllByName(String hostName)

throws UnknownHostException
The getLocalHost( ) method simply returns the InetAddress object that
represents the local host. The getByName( ) method returns an
InetAddress for a host name passed to it. If these methods are unable
to resolve the host name, they throw an UnknownHostException.On
the Internet, it is common for a single name to be used to represent
several machines. In the world of web servers, this is one way to
provide some degree of scaling. The getAllByName( ) factory method
returns an array of InetAddresses that represent all of the addresses
that a particular name resolves to. It will also throw an
UnknownHostException if it can't resolve the name to at least one
address.

The following example prints the addresses and names of the


local machine and two well-known Internet web sites:
// Demonstrate InetAddress.

import java.net.*;

class InetAddressTest

public static void main(String args[]) throws

UnknownHostException {

InetAddress Address = InetAddress.getLocalHost();

System.out.println(Address);

Address = InetAddress.getByName("starwave.com");

System.out.println(Address);

InetAddress SW[] = InetAddress.getAllByName("www.nba.com");

for (int i=0; i<SW.length; i++)

System.out.println(SW[i]);
}

Here is the output produced by this program. (Of course, the output
you see will be slightly different.)

default/206.148.209.138

starwave.com/204.202.129.90

Uses of Class
java.net.InetAddressPackages that use InetAddress

java.lang Provides classes that are fundamental to the design of


the Java

programming language.

java.net Provides the classes for implementing networking


applications.

Uses of InetAddress in java.lang

Methods in java.lang with parameters of type InetAddress

void SecurityManager.checkMulticast(InetAddress maddr)

void SecurityManager.checkMulticast(InetAddress maddr, byte ttl)

Deprecated. Use #checkPermission(java.security.Permission) instead


Uses of InetAddress in java.net
Subclasses of InetAddress in java.net
Class Inet4Address .This class represents an Internet Protocol version
4 (IPv4) address. Class Inet6Address .This class represents an Internet
Protocol version 6 (IPv6) address.

2 Factory method
Provides an abstraction or an interface and lets subclass or
implementing classe decide which class or method should be
instantiated or called, based on the conditions or parameters given.

Benefits:
• Connect parallel class hierarchies.

• A class wants its subclasses to specify the object.

• A class cannot anticipate its subclasses, which must be created.

• A family of objects needs to be separated by using shared


interface.

• The code needs to deal with interface, not implemented classes.

• Hide concrete classes from the client.

• Factory methods can be parameterized.


Related patterns include

 Abstract Factory , which is a layer higher than a factory


method.

 Template method, which defines a skeleton of an


algorithm to defer

some Steps to subclasses or avoid


subclasses

 Prototype, which creates a new object by copying


an instance, it

reduces subclasses.

 Singleton, which makes a returned factory


method unique.

Examples
To illustrate such concept, let's use a simple example. To
paint a picture, you may need several steps. A shape is an
interface. Several implementing classes may be designed in
the following way.
interface Shape {
public void draw();
}
class Line implements Shape {
Point x, y;
Line(Point a, Point b) {
x = a;
y = b;
}
public void draw() {
//draw a line;
}
}
class Square implements Shape {
Point start;
int width, height;
Square(Point s, int w, int h) {
start = s;
width = w;
height = h;
}
public void draw() {
//draw a square;
}
}
class Circle implements Shape {
....
}

class Painting {
Point x, y;
int width, height, radius;
Painting(Point a, Point b, int w, int h, int r) {
x = a;
y = b;
width = w;
height = h;
radius = r;
}
Shape drawLine() {
return new Line(x,y);
}
Shape drawSquare() {
return new Square(x, width, height);
}
Shape drawCircle() {
return new Circle(x, radius);
}
....
}

...
Shape pic;
Painting pt;
//initializing pt
....
if (line)
pic = pt.drawLine();
if (square)
pic = pt.drawSquare();
if (circle)
pic = pt.drawCircle();
3. Uniform Resource Locator (URL)
A Uniform Resource Locator (URL) specifies the location of a resource
on the Web. The HTMLReaderBean class shows how to connect to a
URL from within an enterprise bean.

The source code for this example is in the


j2eetutorial/examples/src/ejb/htmlreader directory. To compile the
code, go to the j2eetutorial/examples directory and type ant
htmlreader. A sample HTMLReaderApp.ear file is in the
j2eetutorial/examples/ears directory.

java.net.URLConnection

1. A URLConnection object represents a connection to a remote


machine.

2. You use it to read a resource from and write to a remote machine.

3. To obtain an instance of URLConnection, call the openConnection


method on a URL object.

4. To use a URLConnection object to write: set the value of doOutput


to true using setDoOutput methods:

URL url = new URL ("http://www.google.com/");


InputStream inputStream = url.openStream ();

has the same effect as

URL url = new URL ("http://www.google.com/");

URLConnection urlConnection = url.openConnection ();


InputStream inputStream = urlConnection.getInputStream ();

The getContents method of the HTMLReaderBean class returns a


String that contains the contents of an HTML file. This method looks up
the java.net.URL object associated with a coded name (url/MyURL),
opens a connection to it, and then reads its contents from an
InputStream. Before deploying the application, you must map the
coded name (url/MyURL) to a JNDI name (a URL string). Here is the
source code for the getContents method.

public StringBuffer getContents() throws


HTTPResponseException

Context context;

URL url;

StringBuffer buffer;

String line;

int responseCode;

HttpURLConnection connection;

InputStream input;

BufferedReader dataInput;

try {

context = new InitialContext();

url = (URL)context.lookup("java:comp/env/url/MyURL");

connection = (HttpURLConnection)url.openConnection();

responseCode = connection.getResponseCode();

} catch (Exception ex) {

throw new EJBException(ex.getMessage());

}
if (responseCode != HttpURLConnection.HTTP_OK) {

throw new HTTPResponseException("HTTP response code: "


+

String.valueOf(responseCode));

try {

buffer = new StringBuffer();

input = connection.getInputStream();

dataInput =

new BufferedReader(new InputStreamReader(input));

while ((line = dataInput.readLine()) != null) {

buffer.append(line);

buffer.append('\n');

} catch (Exception ex) {

throw new EJBException(ex.getMessage());

return buffer;

}
4. File handling:
File handling is an integral part of nearly all programming
projects. Files provide the means by which a program stores data,
accesses stored data, or shares data. As a result, there are very
few applications that don’t interact with a file in one form or
another. Although no aspect of file handling is particularly
difficult, a great many classes, interfaces, and methods are
involved. Being able to effectively apply them to your projects is
the mark of a professional.

Step 1 - Java file handling basics


One of the most frequently used task in programming is writing
to and reading
from a file. To do this in Java there are more possibilities. At
this time only the
most frequently used text file handling solutions will be
presented.

Filename handling

To write anything to a file first of all we need a file name we want


to use. The file name is a simple string like like this:

• String fileName = "test.txt";

If you want to write in a file which is located elsewhere you need


to define the

complete file name and path in your fileName variable:

• String fileName = "c:\\filedemo\\test.txt";

However if you define a path in your file name then you have to
take care the path separator. On windows system the '\' is used
and you need to backslash it so you need to write '\\', in
Unix,Linux systems

the separator is a simple slash '/'.

To make your code OS independent you can get the separator


character as follows:

• String separator = File.separator;


Open a file

To open a file for writing use the FileWriter class and create an
instance from it.

The file name is passed in the constructor like this:

• FileWriter writer = new FileWriter(fileName);

This code opens the file in overwrite mode. If you want to append to
the file then

you need to use an other constructor like this:

• FileWriter writer = new FileWriter(fileName,true);

Besides this the constructor can throw an IOException so we put all of


the code inside

a try-catch block.

Write to file
At this point we have a writer object and we can send real content to
the file. You can do this using the write() method, which has more
variant but the most commonly used requires a string as input
parameter.

Calling the write() method doesn't mean that it immediately writes the
data into the file. The output is maybe cached so if you want to send
your data immediately to the file you need to call the flush() method.

As last step you should close the file with the close() method and you
are done.

The basic write method looks like this:


Code:

1. public void writeFile() {

2. string fileName = "c:\\test.txt";

3. try {

4. FileWriter writer = new FileWriter(fileName,true);

5. writer.write("Test text.");

6. writer.close();

7. }

8. catch (IOException e) {

9. e.printStackTrace();

10. }

11. }

Anda mungkin juga menyukai