Chapter 11
<< Chapter 10 | HomeworkTrailIndex | Chapter 12 >>
Input/Output Exceptions
Demo1: LineNumberer
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
public class LineNumberer
{
public static void main(String[] args)
throws FileNotFoundException
{
Scanner console = new Scanner(System.in);
System.out.print("Output file: ");
String outputFileName = console.next();
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
FileReader reader = new FileReader(chooser.getSelectedFile() );
System.out.println("Adding line numbers to "+chooser.getSelectedFile().getName() );
Scanner in = new Scanner(reader);
PrintWriter out = new PrintWriter(outputFileName);
int lineNumber = 1;
while (in.hasNextLine())
{
String line = in.nextLine();
out.println("/* " + lineNumber + " */ " + line);
lineNumber++;
}
out.close();
in.close();
}
}
}
Any text file like the one below can be used.
Mary.txt
Mary had a little lamb Whose fleece is white as snow Everywhere Mary went Her lamb was sure to go
Demo 2 : Data Analyzer
DataAnalyzer.java
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
/**
This program reads a file containing numbers and analyzes its contents.
If the file doesn't exist or contains strings that are not numbers, an
error message is displayed.
*/
public class DataAnalyzer
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
DataSetReader reader = new DataSetReader();
boolean done = false;
while (!done)
{
try
{
System.out.println("Please enter the file name: ");
String filename = in.next();
double[] data = reader.readFile(filename);
double sum = 0;
for (double d : data) sum = sum + d;
System.out.println("The sum is " + sum);
done = true;
}
catch (FileNotFoundException exception)
{
System.out.println("File not found.");
}
catch (BadDataException exception)
{
System.out.println("Bad data: " + exception.getMessage());
}
catch (IOException exception)
{
exception.printStackTrace();
}
}
}
}
DataSetReader.java
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
/**
Reads a data set from a file. The file must have the format
numberOfValues
value1
value2
. . .
*/
public class DataSetReader
{
/**
Reads a data set.
@param filename the name of the file holding the data
@return the data in the file
*/
public double[] readFile(String filename)
throws IOException, BadDataException
{
FileReader reader = new FileReader(filename);
try
{
Scanner in = new Scanner(reader);
readData(in);
}
finally
{
reader.close();
}
return data;
}
/**
Reads all data.
@param in the scanner that scans the data
*/
private void readData(Scanner in) throws BadDataException
{
if (!in.hasNextInt())
throw new BadDataException("Length expected");
int numberOfValues = in.nextInt();
data = new double[numberOfValues];
for (int i = 0; i < numberOfValues; i++)
readValue(in, i);
if (in.hasNext())
throw new BadDataException("End of file expected");
}
/**
Reads one data value.
@param in the scanner that scans the data
@param i the position of the value to read
*/
private void readValue(Scanner in, int i) throws BadDataException
{
if (!in.hasNextDouble())
throw new BadDataException("Data value expected");
data[i] = in.nextDouble();
}
private double[] data;
}
BadDataException.java
/**
This class reports bad input data.
*/
public class BadDataException extends Exception
{
public BadDataException() {}
public BadDataException(String message)
{
super(message);
}
}
Data files
The following are different input files. Using your operating systems, place a copy of these data files in the same folder where your IDE stores your project.
bad1.dat
10 1 2 3 4 5 6 7 8 9
bad2.dat
ten 1 2 3 4 5 6 7 8 9
bad3.dat
10 one 2 3 4 5 6 7 8 9
bad4.dat
10 1 2 3 4 5 6 7 8 9 10 11
good.dat
10 1 2 3 4 5 6 7 8 9 10
Review Exercises
Programming Exercises
P11.1 Write a program that asks a user for a file name and prints the number of characters, words, and lines in that file.
Use the following class as your main class:
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
/**
This class prints a report on the contents of a file.
*/
public class FileAnalyzer
{
public static void main(String[] args) throws IOException
{
System.out.println("Filename: ");
Scanner in = new Scanner(System.in);
String name = in.nextLine();
FileCounter counter = new FileCounter();
FileReader reader = new FileReader(name);
Scanner fileIn = new Scanner(reader);
counter.read(fileIn);
fileIn.close();
System.out.println("Characters: " + counter.getCharacterCount());
System.out.println("Words: " + counter.getWordCount());
System.out.println("Lines : " + counter.getLineCount());
}
}
FileCounter.java
import java.util.Scanner;
/**
A class to count the number of characters, words, and lines in files.
*/
public class FileCounter
{
/**
Constructs a FileCounter object.
*/
public FileCounter()
{
//Your code here . . .
}
/**
Processes an input source and adds its character, word, and line
counts to this counter.
@param in the scanner to process
*/
public void read(Scanner in)
{
//Your code here. . .
}
/**
Gets the number of words in this counter.
@return the number of words
*/
public int getWordCount()
{
//Your code here. . .
return 0;
}
/**
Gets the number of lines in this counter.
@return the number of lines
*/
public int getLineCount()
{
//Your code here . . .
return 0;
}
/**
Gets the number of characters in this counter.
@return the number of characters
*/
public int getCharacterCount()
{
return 0;
}
}
P11.12 Write a program that asks the user to input a set of floating-point values. When the user enters a value that is not a number, give the user as many chances as necessary to enter a correct value. Quit the input stage of the program when the user enters a blank input. Add all correctly specified values and print the sum when the user is done entering data. Use exception handling to detect improper inputs.
Here is a sample program run:
Value: 1 Value: 2 Value: three Input error. Try again. Value: 3 Value : four Input error. Try again. Value: quartre Input error. Try again. Value: vier Input error. Try again. Value: 4 Value: five Input error. Try again. Value: cinq Input error. Try again. Value: 5 Value: Sum: 15.0
Your main class should be called DataReader.
