Siêu thị PDFTải ngay đi em, trời tối mất

Thư viện tri thức trực tuyến

Kho tài liệu với 50,000+ tài liệu học thuật

© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Advanced Network Programming  Principles and Techniques Network Application Programming with Java
PREMIUM
Số trang
307
Kích thước
3.3 MB
Định dạng
PDF
Lượt xem
1691

Advanced Network Programming Principles and Techniques Network Application Programming with Java

Nội dung xem thử

Mô tả chi tiết

Mercer University

Advanced Java Programming

SSE 554 Spring 2010 – Project 3

TUYEN DO – TUNG NGUYEN - NGOC DONG

4/26/2010

Advanced Java Programming

Page 2

Table of Contents

1 Introduction...........................................................................................................................................3

2 Streams and Files..................................................................................................................................4

2.1 Overview of Stream and Files.......................................................................................................5

2.2 Demonstration of Stream and Files.............................................................................................16

3 XML....................................................................................................................................................21

3.1 Overview of XML.......................................................................................................................21

3.2 Demonstration of XML...............................................................................................................27

4 Database Programming.......................................................................................................................28

4.1 Overview of Database Programming..........................................................................................28

4.2 Demonstration of Database Programming..................................................................................32

5 Internationalization .............................................................................................................................37

5.1 Overview of Internationalization ................................................................................................37

5.2 Demonstration of Internationalization ........................................................................................46

6 Advanced Swing .................................................................................................................................47

6.1 Overview of Advanced Swing ....................................................................................................51

6.2 Demonstration of Advanced Swing ............................................................................................65

7 Advanced AWT ..................................................................................................................................74

7.1 Overview of Advanced AWT .....................................................................................................78

7.2 Demonstration of Advanced AWT .............................................................................................90

8 JavaBeans Components.......................................................................................................................99

8.1 Overview of JavaBeans Components..........................................................................................99

8.2 Demonstration of JavaBeans Components................................................................................152

9 Distributed Objects ...........................................................................................................................185

9.1 Overview of Distributed Objects ..............................................................................................185

9.2 Demonstration of Distributed Objects ......................................................................................224

10 Scripting, Compiling, and Annotation Processing........................................................................237

10.1 Overview of Scripting, Compiling, and Annotation Processing...............................................238

10.2 Demonstration of Scripting, Compiling, and Annotation Processing.......................................281

11 Conclusions/Summary ..................................................................................................................307

References.............................................................................................................................................307

Advanced Java Programming

Page 3

1 Introduction

This Team Project 3 serves as a continuation effort of coding in Java above and beyond the basic

described in Core Java Volume I. The content of this report covers many advanced features

described in Core Java Volume II and some other resources on internets. Topics covered are

Streams and Files, XML, Database Programming, Internationaization, Advanced Swing,

Advanced AWT, JavaBeans Components, Distributed Objects, and Scripting-Compiling-and

Annotation Processing.

Based on our interests, objective of the project and time constrain, this paper covers as much as

possible all concepts and standard features that help to accomplish our goal in providing the

understanding of selected topics. But there is no way to cevered all topics in details and therefore

some of the topics are broadly discussed and refered to references when necessary. The report is

structured simply by two main sections for each topic: basic description, instruction, and

standard followed by demonstration. Basic concepts, techniques, standards on the subject may be

directly excerpted from the sources listed in references where appropriate.

More detailed discussion for particular topic that can not be found in this paper can be found in

Core Java Volume II-Advances features, 8th Edition [1] if preferred.

Advanced Java Programming

Page 4

2 Streams and Files

Streams

In the Java API, an object from which we can read a sequence of bytes is called an input stream.

An object to which we can write a sequence of bytes is called an output stream. These sources

and destinations of byte sequences can be—and often are—files, but they can also be network

connections and even blocks of memory. The abstract classes InputStream and OutputStream

form the basis for a hierarchy of input/output (I/O) classes. Because byte-oriented streams are

inconvenient for processing information stored in Unicode (recall that Unicode uses multiple

bytes per character), there is a separate hierarchy of classes for processing Unicode characters

that inherit from the abstract Reader and Writer classes. These classes have read and write

operations that are based on two-byte Unicode code units rather than on single-byte characters.

I/O Streams

An I/O Stream represents an input source or an output destination. A stream can represent many

different kinds of sources and destinations, including disk files, devices, other programs, and

memory arrays.

Streams support many different kinds of data, including simple bytes, primitive data types,

localized characters, and objects. Some streams simply pass on data; others manipulate and

transform the data in useful ways. No matter how they work internally, all streams present the

same simple model to programs that use them: A stream is a sequence of data. A program uses

an input stream to read data from a source, one item at a time:

Figure 1: Reading information into a program.

Advanced Java Programming

Page 5

A program uses an output stream to write data to a destination, one item at time:

Figure 2: Writing information from a program.

We'll see streams that can handle all kinds of data, from primitive values to advanced objects.

The data source and data destination from figure 2 above can be anything that holds, generates,

or consumes data. Obviously this includes disk files, but a source or destination can also be

another program, a peripheral device, a network socket, or an array.

2.1 Overview of Stream and Files

We will use the most basic kind of streams, byte streams, to demonstrate the common operations

of Stream I/O.

Byte Streams

Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are

descended from InputStream and OutputStream.

There are many byte stream classes. To demonstrate how byte streams work, we'll focus on the

file I/O byte streams, FileInputStream and FileOutputStream. Other kinds of byte streams are

used in much the same way; they differ mainly in the way they are constructed.

Using Byte Streams

We'll explore FileInputStream and FileOutputStream by examining an example program named

CopyBytes, which uses byte streams to copy xanadu.txt, one byte at a time.

import java.io.FileInputStream;

import java.io.FileOutputStream;

Advanced Java Programming

Page 6

import java.io.IOException;

public class CopyBytes {

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

FileInputStream in = null;

FileOutputStream out = null;

try {

in = new FileInputStream("xanadu.txt");

out = new FileOutputStream("outagain.txt");

int c;

while ((c = in.read()) != -1) {

out.write(c);

}

} finally {

if (in != null) {

in.close();

}

if (out != null) {

out.close();

}

}

}

}

CopyBytes spends most of its time in a simple loop that reads the input stream and writes the

output stream, one byte at a time, as shown in the following figure.

Advanced Java Programming

Page 7

Figure 3: Simple byte stream input and output.

Notice that read() returns an int value. If the input is a stream of bytes, why doesn't read() return

a byte value? Using a int as a return type allows read() to use -1 to indicate that it has reached

the end of the stream.

Always Close Streams

Closing a stream when it's no longer needed is very important — so important that CopyBytes

uses a finally block to guarantee that both streams will be closed even if an error occurs. This

practice helps avoid serious resource leaks.

One possible error is that CopyBytes was unable to open one or both files. When that happens,

the stream variable corresponding to the file never changes from its initial null value. That's why

CopyBytes makes sure that each stream variable contains an object reference before invoking

close.

When Not to Use Byte Streams

CopyBytes seems like a normal program, but it actually represents a kind of low-level I/O that

you should avoid. Since xanadu.txt contains character data, the best approach is to use character

streams, as discussed in the next section. There are also streams for more complicated data types.

Byte streams should only be used for the most primitive I/O.

Advanced Java Programming

Page 8

Character Streams

The Java platform stores character values using Unicode conventions. Character stream I/O

automatically translates this internal format to and from the local character set. In Western

locales, the local character set is usually an 8-bit superset of ASCII.

For most applications, I/O with character streams is no more complicated than I/O with byte

streams. Input and output done with stream classes automatically translates to and from the local

character set. A program that uses character streams in place of byte streams automatically

adapts to the local character set and is ready for internationalization — all without extra effort by

the programmer.

If internationalization isn't a priority, you can simply use the character stream classes without

paying much attention to character set issues. Later, if internationalization becomes a priority,

your program can be adapted without extensive recoding. Using Character Streams

All character stream classes are descended from Reader and Writer. As with byte streams, there

are character stream classes that specialize in file I/O: FileReader and FileWriter. The

CopyCharacters example illustrates these classes.

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

public class CopyCharacters {

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

FileReader inputStream = null;

FileWriter outputStream = null;

try {

inputStream = new FileReader("xanadu.txt");

outputStream = new FileWriter("characteroutput.txt");

int c;

while ((c = inputStream.read()) != -1) {

outputStream.write(c);

}

} finally {

if (inputStream != null) {

inputStream.close();

}

if (outputStream != null) {

Advanced Java Programming

Page 9

outputStream.close();

}

}

}

}

CopyCharacters is very similar to CopyBytes. The most important difference is that

CopyCharacters uses FileReader and FileWriter for input and output in place of FileInputStream

and FileOutputStream. Notice that both CopyBytes and CopyCharacters use an int variable to

read to and write from. However, in CopyCharacters, the int variable holds a character value in

its last 16 bits; in CopyBytes, the int variable holds a byte value in its last 8 bits.

Character Streams that Use Byte Streams

Character streams are often "wrappers" for byte streams. The character stream uses the byte

stream to perform the physical I/O, while the character stream handles translation between

characters and bytes. FileReader, for example, uses FileInputStream, while FileWriter uses

FileOutputStream.

There are two general-purpose byte-to-character "bridge" streams: InputStreamReader and

OutputStreamWriter. Use them to create character streams when there are no prepackaged

character stream classes that meet your needs. The sockets lesson in the networking trail shows

how to create character streams from the byte streams provided by socket classes.

Line-Oriented I/O

Character I/O usually occurs in bigger units than single characters. One common unit is the line:

a string of characters with a line terminator at the end. A line terminator can be a carriage￾return/line-feed sequence ("\r\n"), a single carriage-return ("\r"), or a single line-feed ("\n").

Supporting all possible line terminators allows programs to read text files created on any of the

widely used operating systems.

Let's modify the CopyCharacters example to use line-oriented I/O. To do this, we have to use

two classes we haven't seen before, BufferedReader and PrintWriter. We'll explore these

classes in greater depth in Buffered I/O and Formatting. Right now, we're just interested in

their support for line-oriented I/O.

Advanced Java Programming

Page 10

The CopyLines example invokes BufferedReader.readLine and PrintWriter.println to do input

and output one line at a time.

import java.io.FileReader;

import java.io.FileWriter;

import java.io.BufferedReader;

import java.io.PrintWriter;

import java.io.IOException;

public class CopyLines {

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

BufferedReader inputStream = null;

PrintWriter outputStream = null;

try {

inputStream =

new BufferedReader(new FileReader("xanadu.txt"));

outputStream =

new PrintWriter(new FileWriter("characteroutput.txt"));

String l;

while ((l = inputStream.readLine()) != null) {

outputStream.println(l);

}

} finally {

if (inputStream != null) {

inputStream.close();

}

if (outputStream != null) {

outputStream.close();

}

}

}

}

Invoking readLine returns a line of text with the line. CopyLines outputs each line using println,

which appends the line terminator for the current operating system. This might not be the same

line terminator that was used in the input file.

The Complete Stream Zoo

Unlike C, which gets by just fine with a single type FILE*, Java has a whole zoo of more than 60

(!) different stream types (see Figures 4 and 5).

Advanced Java Programming

Page 11

Figure 4. Input and output stream hierarchy.

Advanced Java Programming

Page 12

Figure 5. Reader and writer hierarchy.

Let us divide the animals in the stream class zoo by how they are used. There are separate

hierarchies for classes that process bytes and characters. As you saw, the InputStream and

OutputStream classes let you read and write individual bytes and arrays of bytes. These classes

form the basis of the hiearchy shown in Figure 4. To read and write strings and numbers, you

need more capable subclasses. For example, DataInputStream and DataOutputStream let you

read and write all the primitive Java types in binary format. Finally, there are streams that do

useful stuff; for example, the ZipInputStream and ZipOutputStream that let you read and write

files in the familiar ZIP compression format.

For Unicode text, on the other hand, you use subclasses of the abstract classes Reader and

Writer (see Figure 5). The basic methods of the Reader and Writer classes are similar to the

ones for InputStream and OutputStream.

abstract int read()

Advanced Java Programming

Page 13

abstract void write(int c)

The read method returns either a Unicode code unit (as an integer between 0 and 65535) or -1

when you have reached the end of the file. The write method is called with a Unicode code unit.

Java SE 5.0 introduced four additional interfaces: Closeable, Flushable, Readable, and

Appendable (see Figure 6). The first two interfaces are very simple, with methods

void close() throws IOException

and

void flush()

respectively. The classes InputStream, OutputStream, Reader, and Writer all implement the

Closeable interface. OutputStream and Writer implement the Flushable interface.

Figure 6. The Closeable, Flushable, Readable, and Appendable interfaces.

Combining Stream Filters

FileInputStream and FileOutputStream give you input and output streams attached to a disk file.

You give the file name or full path name of the file in the constructor. For example,

Advanced Java Programming

Page 14

FileInputStream fin = new FileInputStream("employee.dat");

looks in the user directory for a file named "employee.dat".

Like the abstract InputStream and OutputStream classes, these classes support only reading and

writing on the byte level. That is, we can only read bytes and byte arrays from the object fin.

byte b = (byte) fin.read();

As you will see in the next section, if we just had a DataInputStream, then we could read

numeric types:

DataInputStream din = . . .;

double s = din.readDouble();

But just as the FileInputStream has no methods to read numeric types, the DataInputStream has

no method to get data from a file.

Java uses a clever mechanism to separate two kinds of responsibilities. Some streams (such as

the FileInputStream and the input stream returned by the openStream method of the URL class)

can retrieve bytes from files and other more exotic locations. Other streams (such as the

DataInputStream and the PrintWriter) can assemble bytes into more useful data types. The Java

programmer has to combine the two. For example, to be able to read numbers from a file, first

create a FileInputStream and then pass it to the constructor of a DataInputStream.

FileInputStream fin = new FileInputStream("employee.dat");

DataInputStream din = new DataInputStream(fin);

double s = din.readDouble();

If you look at Figure 4 again, you can see the classes FilterInputStream and FilterOutputStream.

The subclasses of these files are used to add capabilities to raw byte streams.

You can add multiple capabilities by nesting the filters. For example, by default, streams are not

buffered. That is, every call to read asks the operating system to dole out yet another byte. It is

more efficient to request blocks of data instead and put them in a buffer. If you want buffering

Advanced Java Programming

Page 15

and the data input methods for a file, you need to use the following rather monstrous sequence of

constructors:

DataInputStream din = new DataInputStream(

new BufferedInputStream(

new FileInputStream("employee.dat")));

Notice that we put the DataInputStream last in the chain of constructors because we want to use

the DataInputStream methods, and we want them to use the buffered read method.

Sometimes you'll need to keep track of the intermediate streams when chaining them together.

For example, when reading input, you often need to peek at the next byte to see if it is the value

that you expect. Java provides the PushbackInputStream for this purpose.

PushbackInputStream pbin = new PushbackInputStream(

new BufferedInputStream(

new FileInputStream("employee.dat")));

Now you can speculatively read the next byte

int b = pbin.read();

and throw it back if it isn't what you wanted.

if (b != '<') pbin.unread(b);

But reading and unreading are the only methods that apply to the pushback input stream. If you

want to look ahead and also read numbers, then you need both a pushback input stream and a

data input stream reference.

DataInputStream din = new DataInputStream(

pbin = new PushbackInputStream(

new BufferedInputStream(

Tải ngay đi em, còn do dự, trời tối mất!