JAVA:
An Introduction to Problem Solving & Programming, 7th
Ed. By Walter Savitch.
ISBN 0133862119 ©
2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved
Listing 9.1 |
import java.util.Scanner;
public class GotMilk
{
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
System.out.println ("Enter number of donuts:");
int donutCount = keyboard.nextInt ();
System.out.println ("Enter number of glasses of milk:");
int milkCount = keyboard.nextInt ();
//Dealing with an unusual event without Javas exception
//handling features:
if (milkCount < 1)
{
System.out.println ("No milk!");
System.out.println ("Go buy some milk.");
}
else
{
double donutsPerGlass = donutCount / (double) milkCount;
System.out.println (donutCount + " donuts.");
System.out.println (milkCount + " glasses of milk.");
System.out.println ("You have " + donutsPerGlass +
" donuts for each glass of milk.");
}
System.out.println ("End of program.");
}
}
|
Listing 9.2 |
import java.util.Scanner;
public class ExceptionDemo
{
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
try
{
System.out.println ("Enter number of donuts:");
int donutCount = keyboard.nextInt ();
System.out.println ("Enter number of glasses of milk:");
int milkCount = keyboard.nextInt ();
if (milkCount < 1)
throw new Exception ("Exception: No milk!");
double donutsPerGlass = donutCount / (double) milkCount;
System.out.println (donutCount + " donuts.");
System.out.println (milkCount + " glasses of milk.");
System.out.println ("You have " + donutsPerGlass +
" donuts for each glass of milk.");
}
catch (Exception e)
{
System.out.println (e.getMessage ());
System.out.println ("Go buy some milk.");
}
System.out.println ("End of program.");
}
}
|
Listing 9.3 |
import java.util.Scanner;
public class ExceptionDemo
{
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
try
{
System.out.println ("Enter number of donuts:");
int donutCount = keyboard.nextInt ();
System.out.println ("Enter number of glasses of milk:");
int milkCount = keyboard.nextInt ();
// assume user enters positive number of glasses of milk
if (milkCount < 1)
throw new Exception ("Exception: No milk!");
// milkCount is positive so exception NOT thrown here
// flow of control continues to here
double donutsPerGlass = donutCount / (double) milkCount;
System.out.println (donutCount + " donuts.");
System.out.println (milkCount + " glasses of milk.");
System.out.println ("You have " + donutsPerGlass
+ " donuts for each glass of milk.");
}// flow of control leaves here
// catch is NOT excecuted
catch (Exception e)
{
System.out.println (e.getMessage ());
System.out.println ("Go buy some milk.");
}
// flow of control comes to here
System.out.println ("End of program.");
}
}
|
Listing 9.4 |
import java.util.Scanner;
public class ExceptionDemo
{
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
try
{
System.out.println ("Enter number of donuts:");
int donutCount = keyboard.nextInt ();
System.out.println ("Enter number of glasses of milk:");
int milkCount = keyboard.nextInt ();
// assume user enters 0 for number of glasses of milk
if (milkCount < 1)
throw new Exception ("Exception: No milk!");
// milkCount is negative so exception IS thrown here
// flow of control jumps to catch block
// flow of control skips past these lines
double donutsPerGlass = donutCount / (double) milkCount;
System.out.println (donutCount + " donuts.");
System.out.println (milkCount + " glasses of milk.");
System.out.println ("You have " + donutsPerGlass
+ " donuts for each glass of milk.");
}
// catch is IS excecuted
catch (Exception e)
{
System.out.println (e.getMessage ());
System.out.println ("Go buy some milk.");
}
// flow of control comes to here after catch block
System.out.println ("End of program.");
}
}
|
Listing 9.5 |
public class DivideByZeroException extends Exception
{
public DivideByZeroException ()
{
super ("Dividing by Zero!");
}
public DivideByZeroException (String message)
{
super (message);
}
}
|
Listing 9.6 |
import java.util.Scanner;
public class DivideByZeroDemo
{
private int numerator;
private int denominator;
private double quotient;
public static void main (String [] args)
{
DivideByZeroDemo oneTime = new DivideByZeroDemo ();
oneTime.doIt ();
}
public void doIt ()
{
try
{
System.out.println ("Enter numerator:");
Scanner keyboard = new Scanner (System.in);
numerator = keyboard.nextInt ();
System.out.println ("Enter denominator:");
denominator = keyboard.nextInt ();
if (denominator == 0)
throw new DivideByZeroException ();
quotient = numerator / (double) denominator;
System.out.println (numerator + "/" + denominator +
" = " + quotient);
}
catch (DivideByZeroException e)
{
System.out.println (e.getMessage ());
giveSecondChance ();
}
System.out.println ("End of program.");
}
public void giveSecondChance ()
{
System.out.println ("Try again:");
System.out.println ("Enter numerator:");
Scanner keyboard = new Scanner (System.in);
numerator = keyboard.nextInt ();
System.out.println ("Enter denominator:");
System.out.println ("Be sure the denominator is not zero.");
denominator = keyboard.nextInt ();
if (denominator == 0)
{
System.out.println ("I cannot do division by zero.");
System.out.println ("Since I cannot do what you want,");
System.out.println ("the program will now end.");
System.exit (0);
}
quotient = ((double) numerator) / denominator;
System.out.println (numerator + "/" + denominator +
" = " + quotient);
}
}
|
Listing 9.7 |
import java.util.Scanner;
public class DoDivision
{
private int numerator;
private int denominator;
private double quotient;
public static void main (String [] args)
{
DoDivision doIt = new DoDivision ();
try
{
doIt.doNormalCase ();
}
catch (DivideByZeroException e)
{
System.out.println (e.getMessage ());
doIt.giveSecondChance ();
}
System.out.println ("End of program.");
}
public void doNormalCase () throws DivideByZeroException
{
System.out.println ("Enter numerator:");
Scanner keyboard = new Scanner (System.in);
numerator = keyboard.nextInt ();
System.out.println ("Enter denominator:");
denominator = keyboard.nextInt ();
if (denominator == 0)
throw new DivideByZeroException ();
quotient = numerator / (double) denominator;
System.out.println (numerator + "/" + denominator +
" = " + quotient);
}
}
|
Listing 9.8 |
import java.util.Scanner;
public class TwoCatchesDemo
{
public static void main (String [] args)
{
try
{
System.out.println ("Enter number of widgets produced:");
Scanner keyboard = new Scanner (System.in);
int widgets = keyboard.nextInt ();
if (widgets < 0)
throw new NegativeNumberException ("widgets");
System.out.println ("How many were defective?");
int defective = keyboard.nextInt ();
if (defective < 0)
throw new NegativeNumberException ("defective widgets");
double ratio = exceptionalDivision (widgets, defective);
System.out.println ("One in every " + ratio +
" widgets is defective.");
}
catch (DivideByZeroException e)
{
System.out.println ("Congratulations! A perfect record!");
}
catch (NegativeNumberException e)
{
System.out.println ("Cannot have a negative number of " +
e.getMessage ());
}
System.out.println ("End of program.");
}
public static double exceptionalDivision (double numerator,
double denominator) throws DivideByZeroException
{
if (denominator == 0)
throw new DivideByZeroException ();
return numerator / denominator;
}
}
|
Listing 9.9 |
public class NegativeNumberException extends Exception
{
public NegativeNumberException ()
{
super ("Negative Number Exception!");
}
public NegativeNumberException (String message)
{
super (message);
}
}
|
Listing 9.10 |
public class UnknownOpException extends Exception
{
public UnknownOpException ()
{
super ("UnknownOpException");
}
public UnknownOpException (char op)
{
super (op + " is an unknown operator.");
}
public UnknownOpException (String message)
{
super (message);
}
}
|
Listing 9.11 |
import java.util.Scanner;
/**
PRELIMINARY VERSION without exception handling.
Simple line-oriented calculator program. The class
can also be used to create other calculator programs.
*/
public class PrelimCalculator
{
private double result;
private double precision = 0.0001;
//Numbers this close to zero are treated as if equal to zero.
public static void main (String [] args)
throws DivideByZeroException,
UnknownOpException
{
PrelimCalculator clerk = new PrelimCalculator ();
System.out.println ("Calculator is on.");
System.out.print ("Format of each line: ");
System.out.println ("operator space number");
System.out.println ("For example: + 3");
System.out.println ("To end, enter the letter e.");
clerk.doCalculation ();
System.out.println ("The final result is " +
clerk.resultValue ());
System.out.println ("Calculator program ending.");
}
public PrelimCalculator ()
{
result = 0;
}
public void reset ()
{
result = 0;
}
public void setResult (double newResult)
{
result = newResult;
}
public double getResult ()
{
return result;
}
/**
Returns n1 op n2, provided op is one of '+', '', '*',or '/'.
Any other value of op throws UnknownOpException.
*/
public double evaluate (char op, double n1, double n2)
throws DivideByZeroException, UnknownOpException
{
double answer;
switch (op)
{
case '+':
answer = n1 + n2;
break;
case '-':
answer = n1 - n2;
break;
case '*':
answer = n1 * n2;
break;
case '/':
if ((-precision < n2) && (n2 < precision))
throw new DivideByZeroException ();
answer = n1 / n2;
break;
default:
throw new UnknownOpException (op);
}
return answer;
}
public void setResult (double newResult)
{
result = newResult;
}
public double getResult ()
{
return result;
}
/**
Returns n1 op n2, provided op is one of '+', '', '*',or '/'.
Any other value of op throws UnknownOpException.
*/
public double evaluate (char op, double n1, double n2)
throws DivideByZeroException, UnknownOpException
{
double answer;
switch (op)
{
case '+':
answer = n1 + n2;
break;
case '-':
answer = n1 - n2;
break;
case '*':
answer = n1 * n2;
break;
case '/':
if ((-precision < n2) && (n2 < precision))
throw new DivideByZeroException ();
answer = n1 / n2;
break;
default:
throw new UnknownOpException (op);
}
return answer;
}
public void doCalculation () throws DivideByZeroException,
UnknownOpException
{
Scanner keyboard = new Scanner (System.in);
boolean done = false;
result = 0;
System.out.println ("result = " + result);
while (!done)
{
char nextOp = (keyboard.next ()).charAt (0);
if ((nextOp == 'e') || (nextOp == 'E'))
done = true;
else
{
double nextNumber = keyboard.nextDouble ();
result = evaluate (nextOp, result, nextNumber);
System.out.println ("result " + nextOp + " " +
nextNumber + " = " + result);
System.out.println ("updated result = " + result);
}
}
}
}
|
Listing 9.12 |
import java.util.Scanner;
/**
Simple line-oriented calculator program. The class
can also be used to create other calculator programs.
*/
public class Calculator
{
private double result;
private double precision = 0.0001;
//Numbers this close to zero are treated as if equal to zero.
public static void main (String [] args)
{
Calculator clerk = new Calculator ();
try
{
System.out.println ("Calculator is on.");
System.out.print ("Format of each line: ");
System.out.println ("operator space number");
System.out.println ("For example: + 3");
System.out.println ("To end, enter the letter e.");
clerk.doCalculation ();
}
catch (UnknownOpException e)
{
clerk.handleUnknownOpException (e);
}
catch (DivideByZeroException e)
{
clerk.handleDivideByZeroException (e);
}
System.out.println ("The final result is " +
clerk.resultValue ());
System.out.println ("Calculator program ending.");
}
public Calculator ()
{
result = 0;
}
public void
handleDivideByZeroException (DivideByZeroException e)
{
System.out.println ("Dividing by zero.");
System.out.println ("Program aborted");
System.exit (0);
}
public void handleUnknownOpException (UnknownOpException e)
{
System.out.println (e.getMessage ());
System.out.println ("Try again from the beginning:");
try
{
System.out.print ("Format of each line: ");
System.out.println ("operator number");
System.out.println ("For example: + 3");
System.out.println ("To end, enter the letter e.");
doCalculation ();
}
catch (UnknownOpException e2)
{
System.out.println (e2.getMessage ());
System.out.println ("Try again at some other time.");
System.out.println ("Program ending.");
System.exit (0);
}
catch (DivideByZeroException e3)
{
handleDivideByZeroException (e3);
}
}
//The methods reset, setResult, getResult, evaluate, and doCalculation
//are the same as in Listing 9.11.
}
|
Listing 9.13 |
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ColorDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 400;
public static final int HEIGHT = 300;
public static final int NUMBER_OF_CHAR = 20;
private JTextField colorName;
public ColorDemo ()
{
setSize (WIDTH, HEIGHT);
WindowDestroyer listener = new WindowDestroyer ();
addWindowListener (listener);
Container contentPane = getContentPane ();
contentPane.setBackground (Color.GRAY);
contentPane.setLayout (new FlowLayout ());
JButton showButton = new JButton ("Show Color");
showButton.addActionListener (this);
contentPane.add (showButton);
colorName = new JTextField (NUMBER_OF_CHAR);
contentPane.add (colorName);
}
public void actionPerformed (ActionEvent e)
{
Container contentPane = getContentPane ();
try
{
contentPane.setBackground (
getColor (colorName.getText ()));
}
catch (UnknownColorException exception)
{
colorName.setText ("Unknown Color");
contentPane.setBackground (Color.GRAY);
}
}
public Color getColor (String name) throws UnknownColorException
{
if (name.equalsIgnoreCase ("RED"))
return Color.RED;
else if (name.equalsIgnoreCase ("WHITE"))
return Color.WHITE;
else if (name.equalsIgnoreCase ("BLUE"))
return Color.BLUE;
else if (name.equalsIgnoreCase ("GREEN"))
return Color.GREEN;
else
throw new UnknownColorException ();
}
}
|
Listing 9.14 |
public class UnknownColorException extends Exception
{
public UnknownColorException ()
{
super ("Unknown Color!");
}
public UnknownColorException (String message)
{
super (message);
}
}
|
Listing 9.15 |
public class ShowColorDemo
{
public static void main (String [] args)
{
ColorDemo gui = new ColorDemo ();
gui.setVisible (true);
}
}
|
Listing 10.1 |
import java.io.PrintWriter; import java.io.FileNotFoundException; import java.util.Scanner; public class TextFileOutputDemo { public static void main (String [] args) { String fileName = "out.txt"; //The name could be read from //the keyboard. PrintWriter outputStream = null; try { outputStream = new PrintWriter (fileName); } catch (FileNotFoundException e) { System.out.println ("Error opening the file " + fileName); System.exit (0); } System.out.println ("Enter three lines of text:"); Scanner keyboard = new Scanner (System.in); for (int count = 1 ; count <= 3 ; count++) { String line = keyboard.nextLine (); outputStream.println (count + " " + line); } outputStream.close (); System.out.println ("Those lines were written to " + fileName); } } |
Listing 10.2 |
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class TextFileInputDemo
{
public static void main (String [] args)
{
String fileName = "out.txt";
Scanner inputStream = null;
System.out.println ("The file " + fileName +
"\ncontains the following lines:\n");
try
{
inputStream = new Scanner (new File (fileName));
}
catch (FileNotFoundException e)
{
System.out.println ("Error opening the file " +
fileName);
System.exit (0);
}
while (inputStream.hasNextLine ())
{
String line = inputStream.nextLine ();
System.out.println (line);
}
inputStream.close ();
}
}
|
Listing 10.3 |
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class TextFileInputDemo2
{
public static void main (String [] args)
{
System.out.print ("Enter file name: ");
Scanner keyboard = new Scanner (System.in);
String fileName = keyboard.next ();
Scanner inputStream = null;
System.out.println ("The file " + fileName + "\n" +
"contains the following lines:\n");
try
{
inputStream = new Scanner (new File (fileName));
}
catch (FileNotFoundException e)
{
System.out.println ("Error opening the file " +
fileName ");
System.exit (0);
}
while (inputStream.hasNextLine ())
{
String line = inputStream.nextLine ();
System.out.println (line);
}
inputStream.close ();
}
}
|
Listing 10.4 |
File: Transactions.txt
SKU,Quantity,Price,Description
4039,50,0.99,SODA
9100,5,9.50,T-SHIRT
1949,30,110.00,JAVA PROGRAMMING TEXTBOOK
5199,25,1.50,COOKIE
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.util.Scanner;
public class TransactionReader
{
public static void main(String[] args)
{
String fileName = "Transactions.txt";
try
{
Scanner inputStream = new Scanner(new File(fileName));
// Read the header line
String line = inputStream.nextLine();
// Total sales
double total = 0;
// Read the rest of the file line by line
while (inputStream.hasNextLine())
{
// Contains SKU,Quantity,Price,Description
line = inputStream.nextLine();
// Turn the string into an array of strings
String[] ary = line.split(",");
// Extract each item
String SKU = ary[0];
int quantity = Integer.parseInt(ary[1]);
double price = Double.parseDouble(ary[2]);
String description = ary[3];
// Output item
System.out.printf("Sold %d of %s (SKU: %s) at $%1.2f each.\n",
quantity, description, SKU, price);
// Compute total
total += quantity * price;
}
System.out.printf("Total sales: $%1.2f\n",total);
inputStream.close( );
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find file " + fileName);
}
catch(IOException e)
{
System.out.println("Problem with input from file " + fileName);
}
}
}
|
Listing 10.5 |
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class BinaryOutputDemo
{
public static void main (String [] args)
{
String fileName = "numbers.dat";
try
{
ObjectOutputStream outputStream =
new ObjectOutputStream (new FileOutputStream (fileName));
Scanner keyboard = new Scanner (System.in);
System.out.println ("Enter nonnegative integers.");
System.out.println ("Place a negative number at the end.");
int anInteger;
do
{
anInteger = keyboard.nextInt ();
outputStream.writeInt (anInteger);
}
while (anInteger >= 0);
System.out.println ("Numbers and sentinel value");
System.out.println ("written to the file " + fileName);
outputStream.close ();
}
catch (FileNotFoundException e)
{
System.out.println ("Problem opening the file " + fileName);
}
catch (IOException e)
{
System.out.println ("Problem with output to file " + fileName);
}
}
}
|
Listing 10.6 |
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class BinaryInputDemo
{
public static void main (String [] args)
{
String fileName = "numbers.dat";
try
{
ObjectInputStream inputStream =
new ObjectInputStream (new FileInputStream (fileName));
System.out.println ("Reading the nonnegative integers");
System.out.println ("in the file " + fileName);
int anInteger = inputStream.readInt ();
while (anInteger >= 0)
{
System.out.println (anInteger);
anInteger = inputStream.readInt ();
}
System.out.println ("End of reading from file.");
inputStream.close ();
}
catch (FileNotFoundException e)
{
System.out.println ("Problem opening the file " + fileName);
}
catch (EOFException e)
{
System.out.println ("Problem reading the file " + fileName);
System.out.println ("Reached end of the file.");
}
catch (IOException e)
{
System.out.println ("Problem eading the file " + fileName);
}
}
}
|
Listing 10.7 |
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
public class EOFExceptionDemo
{
public static void main (String [] args)
{
String fileName = "numbers.dat";
try
{
ObjectInputStream inputStream =
new ObjectInputStream (new FileInputStream (fileName));
System.out.println ("Reading ALL the integers");
System.out.println ("in the file " + fileName);
try
{
while (true)
{
int anInteger = inputStream.readInt ();
System.out.println (anInteger);
}
}
catch (EOFException e)
{
System.out.println ("End of reading from file.");
}
inputStream.close ();
}
catch (FileNotFoundException e)
{
System.out.println ("Cannot find file " + fileName);
}
catch (IOException e)
{
System.out.println ("Problem with input from file " + fileName);
}
}
}
|
Listing 10.8 |
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class Doubler
{
private ObjectInputStream inputStream = null;
private ObjectOutputStream outputStream = null;
/**
Doubles the integers in one file and puts them in another file.
*/
public static void main (String [] args)
{
Doubler twoTimer = new Doubler ();
twoTimer.connectToInputFile ();
twoTimer.connectToOutputFile ();
twoTimer.timesTwo ();
twoTimer.closeFiles ();
System.out.println ("Numbers from input file");
System.out.println ("doubled and copied to output file.");
}
public void connectToInputFile ()
{
String inputFileName =
getFileName ("Enter name of input file:");
try
{
inputStream = new ObjectInputStream (
new FileInputStream (inputFileName));
}
catch (FileNotFoundException e)
{
System.out.println ("File " + inputFileName +
" not found.");
System.exit (0);
}
catch (IOException e)
{
System.out.println ("Error opening input file " +
inputFileName);
System.exit (0);
}
}
private String getFileName (String prompt)
{
String fileName = null;
System.out.println (prompt);
Scanner keyboard = new Scanner (System.in);
fileName = keyboard.next ();
return fileName;
}
public void connectToOutputFile ()
{
String outputFileName =
getFileName ("Enter name of output file:");
try
{
outputStream = new ObjectOutputStream (
new FileOutputStream (outputFileName));
}
catch (IOException e)
{
System.out.println ("Error opening output file " +
outputFileName);
System.out.println (e.getMessage ());
System.exit (0);
}
}
public void timesTwo ()
{
try
{
while (true)
{
int next = inputStream.readInt ();
outputStream.writeInt (2 * next);
}
}
catch (EOFException e)
{
//Do nothing. This just ends the loop.
}
catch (IOException e)
{
System.out.println (
"Error: reading or writing files.");
System.out.println (e.getMessage ());
System.exit (0);
}
}
public void closeFiles ()
{
try
{
inputStream.close ();
outputStream.close ();
}
catch (IOException e)
{
System.out.println ("Error closing files " +
e.getMessage ());
System.exit (0);
}
}
}
|
Listing 10.9 |
import java.io.Serializable; import java.util.Scanner; /** Serialized class for data on endangered species. */ public class Species implements Serializable { private String name; private int population; private double growthRate; public Species () { name = null; population = 0; growthRate = 0; } public Species (String initialName, int initialPopulation, double initialGrowthRate) { name = initialName; if (initialPopulation >= 0) population = initialPopulation; else { System.out.println ("ERROR: Negative population."); System.exit (0); } growthRate = initialGrowthRate; } public String toString () { return ("Name = " + name + "\n" + "Population = " + population + "\n" + "Growth rate = " + growthRate + "%"); } //Other methods are the same as those in Listing 5.17 of Chapter 5, //but they are not needed for the discussion in this chapter. } |
Listing 10.10 |
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ClassObjectIODemo
{
public static void main (String [] args)
{
ObjectOutputStream outputStream = null;
String fileName = "species.records";
try
{
outputStream = new ObjectOutputStream (
new FileOutputStream (fileName));
}
catch (IOException e)
{
System.out.println ("Error opening output file " +
fileName + ".");
System.exit (0);
}
Species califCondor =
new Species ("Calif. Condor", 27, 0.02);
Species blackRhino =
new Species ("Black Rhino", 100, 1.0);
try
{
outputStream.writeObject (califCondor);
outputStream.writeObject (blackRhino);
outputStream.close ();
}
catch (IOException e)
{
System.out.println ("Error writing to file " +
fileName + ".");
System.exit (0);
}
System.out.println ("Records sent to file " +
fileName + ".");
System.out.println (
"Now let's reopen the file and echo the records.");
ObjectInputStream inputStream = null;
try
{
inputStream = new ObjectInputStream (
new FileInputStream ("species.records"));
}
catch (IOException e)
{
System.out.println ("Error opening input file " +
fileName + ".");
System.exit (0);
}
Species readOne = null, readTwo = null;
try
{
readOne = (Species) inputStream.readObject ();
readTwo = (Species) inputStream.readObject ();
inputStream.close ();
}
catch (Exception e)
{
System.out.println ("Error reading from file " +
fileName + ".");
System.exit (0);
}
System.out.println ("The following were read\n" +
"from the file " + fileName + ".");
System.out.println (readOne);
System.out.println ();
System.out.println (readTwo);
System.out.println ("End of program.");
}
}
|
Listing 10.11 |
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ArrayIODemo
{
public static void main (String [] args)
{
Species [] oneArray = new Species [2];
oneArray [0] = new Species ("Calif. Condor", 27, 0.02);
oneArray [1] = new Species ("Black Rhino", 100, 1.0);
String fileName = "array.dat";
try
{
ObjectOutputStream outputStream =
new ObjectOutputStream (
new FileOutputStream (fileName));
outputStream.writeObject (oneArray);
outputStream.close ();
}
catch (IOException e)
{
System.out.println ("Error writing to file " +
fileName + ".");
System.exit (0);
}
System.out.println ("Array written to file " +
fileName + " and file is closed.");
System.out.println ("Open the file for input and " +
"echo the array.");
Species [] anotherArray = null;
try
{
ObjectInputStream inputStream =
new ObjectInputStream (
new FileInputStream (fileName));
anotherArray = (Species []) inputStream.readObject ();
inputStream.close ();
}
catch (Exception e)
{
System.out.println ("Error reading file " +
fileName + . );
System.exit (0);
}
System.out.println ("The following were read from " +
"the file " + fileName + ":");
for (int i = 0 ; i < anotherArray.length ; i++)
{
System.out.println (anotherArray [i]);
System.out.println ();
}
System.out.println ("End of program.");
}
}
|
Listing 10.12 |
import java.util.Scanner;
import java.io.InputStreamReader;
import java.io.DataOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.ServerSocket;
public class SocketServer
{
public static void main(String[] args)
{
String s;
Scanner inputStream = null;
PrintWriter outputStream = null;
ServerSocket serverSocket = null;
try
{
// Wait for connection on port 6789
System.out.println("Waiting for a connection.");
serverSocket = new ServerSocket(6789);
Socket socket = serverSocket.accept();
// Connection made, set up streams
inputStream = new Scanner(new InputStreamReader(socket.getInputStream()));
outputStream = new PrintWriter(new DataOutputStream(socket.getOutputStream()));
// Read a line from the client
s = inputStream.nextLine();
// Output text to the client
outputStream.println("Well, ");
outputStream.println(s + " is a fine programming language!");
outputStream.flush();
System.out.println("Closing connection from " + s);
inputStream.close();
outputStream.close();
}
catch (Exception e)
{
// If any exception occurs, display it
System.out.println("Error " + e);
}
}
}
|
Listing 10.13 |
import java.util.Scanner;
import java.io.InputStreamReader;
import java.io.DataOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class SocketClient
{
public static void main(String[] args)
{
String s;
Scanner inputStream = null;
PrintWriter outputStream = null;
try
{
// Connect to server on same machine, port 6789
Socket clientSocket = new Socket("localhost",6789);
// Set up streams to send/receive data
inputStream = new Scanner(new InputStreamReader(clientSocket.getInputStream()));
outputStream = new PrintWriter(new DataOutputStream(clientSocket.getOutputStream()));
// Send "Java" to the server
outputStream.println("Java");
outputStream.flush(); // Sends data to the stream
// Read everything from the server until no more lines
// and output it to the screen
while (inputStream.hasNextLine())
{
s = inputStream.nextLine();
System.out.println(s);
}
inputStream.close();
outputStream.close();
}
catch (Exception e)
{
// If any exception occurs, display it
System.out.println("Error " + e);
}
}
}
|
Listing 10.14 |
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileOrganizer extends JFrame implements ActionListener
{
public static final int WIDTH = 400;
public static final int HEIGHT = 300;
public static final int NUMBER_OF_CHAR = 30;
private JTextField fileNameField;
private JTextField firstLineField;
public FileOrganizer ()
{
setSize (WIDTH, HEIGHT);
WindowDestroyer listener = new WindowDestroyer ();
addWindowListener (listener);
Container contentPane = getContentPane ();
contentPane.setLayout (new FlowLayout ());
JButton showButton = new JButton ("Show first line");
showButton.addActionListener (this);
contentPane.add (showButton);
JButton removeButton = new JButton ("Remove file");
removeButton.addActionListener (this);
contentPane.add (removeButton);
JButton resetButton = new JButton ("Reset");
resetButton.addActionListener (this);
contentPane.add (resetButton);
fileNameField = new JTextField (NUMBER_OF_CHAR);
contentPane.add (fileNameField);
fileNameField.setText ("Enter file name here.");
firstLineField = new JTextField (NUMBER_OF_CHAR);
contentPane.add (firstLineField);
}
public void actionPerformed (ActionEvent e)
{
String actionCommand = e.getActionCommand ();
if (actionCommand.equals ("Show first line"))
showFirstLine ();
else if (actionCommand.equals ("Remove file"))
removeFile ();
else if (actionCommand.equals ("Reset"))
resetFields ();
else
firstLineField.setText ("Unexpected error.");
}
private void showFirstLine ()
{
Scanner fileInput = null;
String fileName = fileNameField.getText ();
File fileObject = new File (fileName);
if (!fileObject.exists ())
firstLineField.setText ("No such file");
else if (!fileObject.canRead ())
firstLineField.setText ("That file is not readable.");
else
{
try
{
fileInput = new Scanner (fileObject);
}
catch (FileNotFoundException e)
{
firstLineField.setText ("Error opening the file " +
fileName);
}
String firstLine = fileInput.nextLine ();
firstLineField.setText (firstLine);
fileInput.close ();
}
}
private void resetFields ()
{
fileNameField.setText ("Enter file name here.");
firstLineField.setText ("");
}
private void removeFile ()
{
Scanner fileInput = null;
String firstLine;
String fileName = fileNameField.getText ();
File fileObject = new File (fileName);
if (!fileObject.exists ())
firstLineField.setText ("No such file");
else if (!fileObject.canWrite ())
firstLineField.setText ("Permission denied.");
else
{
if (fileObject.delete ())
firstLineField.setText ("File deleted.");
else
firstLineField.setText ("Could not delete file.");
}
}
public static void main (String [] args)
{
FileOrganizer gui = new FileOrganizer ();
gui.setVisible (true);
}
}
|