home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Java 1.2 How-To
/
JavaHowTo.iso
/
code
/
ch10.txt
< prev
next >
Wrap
Text File
|
1998-12-14
|
23KB
|
1,027 lines
WriteStream.java:
import java.io.*;
public class WriteStream
{
// This program runs as an application
public static void main(String[] arguments)
{
//Create an array of data to print
int[] allBytes = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30};
try
{
//declare a stream
FileOutputStream ofile = new σFileOutputStream("bytes.dat");
for (int i=0; i < allBytes.length; i++)
//write to the stream
ofile.write(allBytes[i]);
ofile.close();
} catch (IOException e)// handle any errors
{
System.out.println("Error - " + e.toString());
}//catch
}//main
}//WriteStream
ReadStream.java:
import java.io.*;
public class ReadStream
{
// This program runs as an application
public static void main(String[] arguments)
{
try
{
//declare a stream
FileInputStream ifile = new FileInputStream("bytes.dat");
boolean eof = false;
int cntBytes = 0;
while (!eof)
{
int thisVal = ifile.read();
System.out.print( thisVal + " ");
if (thisVal == -1)
eof = true;
else
cntBytes++;
} //while
ifile.close();
System.out.print("\nBytes read: " + cntBytes);
} catch (IOException e)// handle any errors
{
System.out.println("Error - " + e.toString());
}//catch
}//main
}//ReadStream
BufferedWriteStream.java:
import java.io.*;
public class BufferedWriteStream
{
// This program runs as an application
public static void main(String[] arguments)
{
//Create an array of data to print
int[] allBytes = {1,3,5,7,9,11,13,15,17,19,21,23,25,27,29};
try
{
//declare a stream
FileOutputStream ofile = new FileOutputStream("bufBytes.dat");
BufferedOutputStream bufStream = new BufferedOutputStream(ofile);
for (int i=0; i < allBytes.length; i++)
//write to the stream
bufStream.write(allBytes[i]);
bufStream.close();
} catch (IOException e)// handle any errors
{
System.out.println("Error - " + e.toString());
}//catch
}//main
}//BufferedWriteStream
BufferedReadStream.java:
import java.io.*;
public class BufferedReadStream
{
// This program runs as an application
public static void main(String[] arguments)
{
try
{
//declare a stream
FileInputStream ifile = new FileInputStream("bufBytes.dat");
BufferedInputStream bufStream = new BufferedInputStream(ifile);
boolean eof = false;
int cntBytes = 0;
while (!eof)
{
int thisVal = bufStream.read();
System.out.print( thisVal + " ");
if (thisVal == -1)
eof = true;
else
cntBytes++;
} //while
bufStream.close();
System.out.print("\nBytes read: " + cntBytes);
} catch (IOException e)// handle any errors
{
System.out.println("Error - " + e.toString());
}//catch
}//main
}//BufferedReadStream
BufferedWriteDataStream.java:
import java.io.*;
public class BufferedWriteDataStream
{
// This program runs as an application
public static void main(String[] arguments)
{
//Create an array of data to print
double[] allDoubles = {1.1,3.1,5.1,7.1,9.1,11.1,13.1,15.1,17.1,19.1,21.1,23.1,25.1,27.1,29.1};
try
{
//declare a stream and attach it to a file
FileOutputStream ofile = new FileOutputStream("bufDouble.dat");
//declare a buffer and attach it to a stream
BufferedOutputStream bufStream = new BufferedOutputStream(ofile);
//declare a data stream and assign it to a buffer
DataOutputStream datStream = new DataOutputStream(bufStream);
for (int i=0; i < allDoubles.length; i++)
//write to the datastream
datStream.writeDouble(allDoubles[i]);
datStream.close();
} catch (IOException e)// handle any errors
{
System.out.println("Error - " + e.toString());
}//catch
}//main
}//BufferedWriteDataStream
BufferedReadDataStream.java:
import java.io.*;
public class BufferedReadDataStream
{
// This program runs as an application
public static void main(String[] arguments)
{
try
{
//declare a stream
FileInputStream ifile = new FileInputStream("bufDouble.dat");
BufferedInputStream bufStream = new BufferedInputStream(ifile);
DataInputStream datStream = new DataInputStream(bufStream);
int cntDoubles = 0;
try
{
while (true)
{
double thisVal = datStream.readDouble();
System.out.print( thisVal + " ");
cntDoubles++;
} //while
} catch (EOFException eof)
{
datStream.close();
System.out.print("\nDoubles read: " + [ccc]
cntDoubles);
} //catch
} catch (IOException e)// handle any errors
{
System.out.println("Error - " + e.toString());
}//catch
}//main
}//BufferedReadDataStream
BufferedWriteCharStream.java:
import java.io.*;
public class BufferedWriteCharStream
{
// This program runs as an application
public static void main(String[] arguments)
{
//Create an array of data to print
char[] allChars = {'H','e','l','l','o',' ','W','o','r','l','d','\n'};
try
{
//declare a stream and attach it to a file
FileWriter ofile = new FileWriter("bufChar.dat");
//declare a BufferedWriter - attach it to a stream
BufferedWriter bufStream = new BufferedWriter(ofile);
for (int i=0; i < allChars.length; i++)
//write to the char stream
bufStream.write(allChars[i]);
bufStream.close();
} catch (IOException e)// handle any errors
{
System.out.println("Error - " + e.toString());
}//catch
}//main
}//BufferedWriteCharStream
BufferedReadCharStream.java:
import java.io.*;
public class BufferedReadCharStream
{
// This program runs as an application
public static void main(String[] arguments)
{
try
{
//declare a stream
FileReader ifile = new FileReader("bufChar.dat");
BufferedReader bufStream = new BufferedReader(ifile);
boolean eof = false;
while (!eof)
{
String line = bufStream.readLine();
if (line == null)
eof = true;
else
System.out.println(line);
}//while
bufStream.close();
} catch (IOException e)// handle any errors
{
System.out.println("Error - " + e.toString());
}//catch
}//main
}//BufferedReadStream
GetInetFile.java:
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class GetInetFile extends Frame implements Runnable
{
Thread thread1;
URL doc;
TextArea body = new TextArea("Getting text...");
public GetInetFile()
{
super("Get URL");
add(body);
try
{
doc = new URL("http://www.lads.com/ads/launch.html");
}//try
catch (MalformedURLException e)
{
System.out.println("Bad URL: " + doc);
}//catch
}//GetInetFile
public static void main(String[] arguments)
{
GetInetFile frame1 = new GetInetFile();
WindowListener l = new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}//windowClosing
};//WindowListener
frame1.addWindowListener(l);
frame1.pack();
frame1.setVisible(true);
if (frame1.thread1 == null)
{
frame1.thread1 = new Thread(frame1);
frame1.thread1.start();
}//null
}//main
public void run()
{
URLConnection URLConn = null;
InputStreamReader inStream;
BufferedReader info;
String line1;
StringBuffer strBuffer = new StringBuffer();
try
{
URLConn = this.doc.openConnection();
URLConn.connect();
body.setText("Connection opened ... ");
inStream = new InputStreamReader(URLConn.getInputStream());
info = new BufferedReader(inStream);
body.setText("Reading data ...");
while ((line1 = info.readLine()) != null)
{
strBuffer.append(line1 + "\n");
}//while
body.setText(strBuffer.toString());
}//try
catch (IOException e)
{
System.out.println("IO Error:" + e.getMessage());
}//catch
}//run
}// class Getfile
Advertiser.java:
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.net.*;
/*
* A class which performs the banner animation
*/
class Banner extends Panel implements Runnable{
/*
* an instance of the applet for
* invoking methods from Advertiser class
*/
Advertiser advertiser;
/*
* instance of thread used for animation
*/
Thread thread;
/*
* the next banner image to be displayed
*/
Image theImage;
/*
* width and height of the new banner image
*/
int img_width, img_height;
/*
* offscreen image for double-buffering
*/
Image offscreen;
/*
* offg1 is the graphics object associated with
* offscreen image. offg2 is the clipped version
* of offg1
*/
Graphics offg1, offg2;
/*
* xstart, ystart - x and y coordinate of clipping rectangle
* width, height - width and height of clipping rectangle
* effect_type - the effect type applied the next image
*/
int xstart, ystart, width, height, effect_type;
/**
* constructor just saves instance of the applet
* @param advertiser - instance of Advertiser applet
*/
Banner (Advertiser advertiser) {
this.advertiser = advertiser;
}
/*
* thread that calls repaint() every 25 ms
* to effect animation
*/
public void run() {
Dimension d = getSize();
offscreen = createImage (d.width, d.height);
offg1 = offscreen.getGraphics ();
offg1.setFont (getFont ());
offg1.setColor (Color.gray);
offg1.fillRect (0, 0, d.width, d.height);
while (true) {
repaint ();
try {
Thread.sleep (25);
} catch (InterruptedException e) {
break;
}
}
}
/**
* override update() method to avoid erase flicker
* this is where the drawing is done
* @param g - destination graphics object
*/
public synchronized void update(Graphics g) {
int i, x, y, w, h;
switch (effect_type) {
case 0:
offg1.drawImage (theImage, 0, 0, null);
break;
case 1: // barn-door open
if (xstart > 0) {
xstart -= 5;
width += 10;
offg2 = offg1.create (xstart, 0, width, height);
offg2.drawImage (theImage, -xstart, 0, null);
} else offg1.drawImage (theImage, 0, 0, null);
break;
case 2: // venetian blind
if (height < 10) {
height += 1;
for (y=0; y<img_height; y+=10) {
offg2 = offg1.create (0, y, width, height);
offg2.drawImage (theImage, 0, -y, null);
}
} else offg1.drawImage (theImage, 0, 0, null);
break;
case 3: // checker board
if (width <= 20) {
if (width <= 10) {
i = 0;
for (y=0; y<img_height; y+=10) {
for (x=(i&1)*10; x<img_width; x+=20) {
offg2 = offg1.create (x, y, width, 10);
offg2.drawImage (theImage, -x, -y, null);
}
i += 1;
}
} else {
i = 1;
for (y=0; y<img_height; y+=10) {
for (x=(i&1)*10; x<img_width; x+=20) {
offg2 = offg1.create (x, y, width-10, 10);
offg2.drawImage (theImage, -x, -y, null);
}
i += 1;
}
}
width += 5;
} else offg1.drawImage (theImage, 0, 0, null);
break;
}
g.drawImage (offscreen, 0, 0, null);
}
/**
* Initialize variables for clipping rectangle
* depending on effect type
* @param which - the effect type for next image
* @param img - the next image
*/
public void effect (int which, Image img) {
img_width = img.getWidth (null);
img_height = img.getHeight (null);
theImage = img;
switch (which) {
case 0:
break;
case 1: // barn door
xstart = img_width >> 1;
width = 0;
height = img_height;
break;
case 2:
width = img_width;
height = 0;
break;
case 3:
width = 0;
break;
}
effect_type = which;
}
/*
* Start the repaint thread
*/
public void start() {
thread = new Thread(this);
thread.start();
}
/*
* Stop the repaint thread
*/
public void stop() {
if (thread != null)
thread = null;
}
}
/*
* the Advertiser class proper
*/
public class Advertiser extends Applet implements Runnable, MouseListener {
/*
* instance of Banner
*/
Banner panel;
/*
* instance of thread for cycling effects
* for each new image
*/
Thread thread;
/*
* the total number of images
*/
int NBanners;
/*
* the array of images
*/
Image img[] = new Image[10];
/*
* the delay (dwell) time in milliseconds for each image
*/
int delay[] = new int[10];
/*
* the effect type for each image
*/
int effect[] = new int[10];
/*
* the URL to go to for each image
*/
URL url[] = new URL[10];
/*
* the index variable pointing to the
* current image, delay time, and associated URL
*/
int current = 0;
/*
* called when applet is loaded
* add the banner panel, load images, and parse applet
* parameters
*/
public void init() {
int i;
setLayout(new BorderLayout());
panel = new Banner (this);
panel.addMouseListener(this);
add("Center", panel);
NBanners = 0;
MediaTracker tracker = new MediaTracker (this);
for (i=1; i<=10; i+=1) {
String param, token;
int j, next;
param = getParameter ("T"+i);
if (param == null) break;
StringTokenizer st = new StringTokenizer (param, " ,");
token = st.nextToken ();
img[NBanners] = getImage (getDocumentBase(), token);
tracker.addImage (img[NBanners], i);
showStatus ("Getting image: "+token);
try {
tracker.waitForID (i);
} catch (InterruptedException e) { }
token = st.nextToken ();
delay[NBanners] = Integer.parseInt (token);
token = st.nextToken ();
effect[NBanners] = Integer.parseInt (token);
token = st.nextToken ();
try {
url[NBanners] = new URL (token);
} catch (MalformedURLException e) {
url[NBanners] = null;
}
NBanners += 1;
}
}
/*
* thread that starts the next image transition
*/
public void run () {
while (true) {
panel.effect (effect[current], img[current]);
try {
Thread.sleep (delay[current]);
} catch (InterruptedException e) { }
current += 1;
current %= NBanners;
}
}
/*
* called when applet is started
* start both threads
*/
public void start() {
panel.start();
thread = new Thread(this);
thread.start();
}
/*
* called when applet is stopped
* stops all threads
*/
public void stop() {
panel.stop();
if (thread != null)
thread = null;
}
/**
* Called when user clicks in the applet
* Force the browser to show the associated URL
* MouseListener required methods*/
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mousePressed(MouseEvent e)
{
if (url[current] != null)
{
System.out.println("current " + url[current]);
getAppletContext().showDocument (url[current]);
}
}
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
}
Lookup.java:
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.applet.*;
/*
* Lookup application class
*/
public class Lookup extends Applet implements ActionListener {
/*
* text field for host name
*/
TextField nameField;
Button btnLookup;
/*
* text area for displaying Internet addresses
*/
TextArea addrArea;
/*
* instance of InetAddress needed for name-to-address
* translation
*/
InetAddress inetAddr;
/*
* insertion point in the Internet address
* text area
*/
int insertIndex;
/*
* constructor creates user interface
*/
public void init () {
super.init();
setLayout (new BorderLayout ());
Panel editPanel = new Panel ();
editPanel.setLayout (new BorderLayout ());
editPanel.add ("North", new Label ("Host name"));
nameField = new TextField ("", 32);
btnLookup = new Button("Lookup");
editPanel.add ("Center", nameField);
editPanel.add ("South", btnLookup);
add ("North", editPanel);
Panel areaPanel = new Panel ();
areaPanel.setLayout (new BorderLayout ());
addrArea = new TextArea ("", 24, 32);
addrArea.setEditable (false);
areaPanel.add ("North", new Label ("Internet address"));
areaPanel.add ("Center", addrArea);
add ("Center", areaPanel);
btnLookup.addActionListener(this);
insertIndex = 0;
setSize (300, 200);
}
public void actionPerformed(ActionEvent ev)
{
String name = nameField.getText ();
try
{
inetAddr = InetAddress.getByName (name);
String str = inetAddr.toString () + "\n";
addrArea.insert (str, insertIndex);
insertIndex += str.length ();
} catch (UnknownHostException ex)
{
String str = name + "/ No such host\n";
addrArea.insert (str, insertIndex);
insertIndex += str.length ();
}
}
} // end of Applet
Ping.java:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
/*
* application class
*/
public class Ping extends Frame implements Runnable, ActionListener {
/*
* instance of Socket used for determining
* whether remote host is alive
*/
Socket socket;
/*
* hostname text entry field
*/
TextField addrField;
/*
* the stop button
*/
Button stopButton;
Button startButton;
/*
* the text area for printing remote
* host status
*/
TextArea content;
/*
* thread used to decouple user activity
* from socket activity
*/
Thread thread;
/*
* text area insert position
*/
int insertPos;
/*
* constructor creates user interface
*/
public Ping () {
int i;
setTitle ("Ping");
setLayout(new BorderLayout());
addrField = new TextField ("", 20);
startButton = new Button ("Start");
stopButton = new Button ("Stop");
content = new TextArea ("", 24, 80);
content.setEditable (false);
insertPos = 0;
Panel p = new Panel ();
p.setLayout (new FlowLayout ());
p.add (addrField);
p.add (startButton);
p.add (stopButton);
startButton.addActionListener(this);
stopButton.addActionListener(this);
addWindowListener(new WindowCloser());
add ("North", p);
add ("Center", content);
thread = new Thread (this);
setSize (400, 300);
show ();
}
/**
* handle action events
* Enter keypress starts socket open thread
* Stop button click stops socket thread
* @param evt - event object
* @param obj - object receiving this event
*/
public void actionPerformed (ActionEvent ev)
{
Object object1 = ev.getSource();
if (object1 == startButton)
{
if (thread != null)
thread = null;
thread = new Thread (this);
thread.start ();
}
if (object1 == stopButton)
{
if (thread!= null)
thread = null;
}
}
/*
* socket open thread
* tries to open the telnet port (23)
*/
public void run () {
String name;
name = addrField.getText ();
try {
try {
socket = new Socket (name, 23);
} catch (UnknownHostException e) {
insertString (name+" :unknown host\n");
return;
}
} catch (IOException e2) {
insertString ("Unable to open socket\n");
return;
}
insertString (name + " is alive\n");
try {
socket.close ();
} catch (IOException e2) {
insertString ("IOException closing socket\n");
return;
}
}
/**
* helper method for adding text to the end
* of the text area
* @param s - text to add
*/
void insertString (String s) {
content.insert (s, insertPos);
insertPos += s.length ();
}
/**
* application entry point
* @param args - command-line arguments
*/
public static void main (String args[]) {
new Ping ();
}
}
class WindowCloser extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
Window win = e.getWindow();
win.setVisible(false);
win.dispose();
System.exit(0);
}
}