Chapter 12 Exception Handling and Text IO
Chapter 12 Exception Handling and Text IO
and Text IO
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 1
Motivations
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 2
Objectives
To get an overview of exceptions and exception handling (§12.2).
To explore the advantages of using exception handling (§12.2).
To distinguish exception types: Error (fatal) vs. Exception (nonfatal) and checked vs. unchecked (§12.3).
To declare exceptions in a method header (§12.4.1).
To throw exceptions in a method (§12.4.2).
To write a try-catch block to handle exceptions (§12.4.3).
To explain how an exception is propagated (§12.4.3).
To obtain information from an exception object (§12.4.4).
To develop applications with exception handling (§12.4.5).
To use the finally clause in a try-catch block (§12.5).
To use exceptions only for unexpected errors (§12.6).
To rethrow exceptions in a catch block (§12.7).
To create chained exceptions (§12.8).
To define custom exception classes (§12.9).
To discover file/directory properties, to delete and rename files/directories, and to create directories using the
File class (§12.10).
To write data to a file using the PrintWriter class (§12.11.1).
To use try-with-resources to ensure that the resources are closed automatically (§12.11.2).
To read data from a file using the Scanner class (§12.11.3).
To develop a program that replaces text in a file (§12.11.5).
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 3
Exception-Handling Overview
Runtime errors occur while a program is running
if the JVM detects an operation that is impossible
to carry out.
– Examples: array index out of bound, divide by zero,
input mismatch
Exception handling enables a program to deal with
exceptional situations and continue its normal
execution.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 4
Exception-Handling Overview
Runtime errors are thrown as exceptions.
An exception is an object that represents an
error or a condition that prevents execution
from proceeding normally.
If the exception is not handled, the program
will terminate abnormally.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 5
import java.util.Scanner; Example #1
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 6
import java.util.Scanner; Example #2
QuotientWithMethod
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 7
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Example #2
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
try {
int result = quotient(number1, number2);
System.out.println(number1 + " / " + number2 + " is " + result);
}
catch (ArithmeticException ex) {
System.out.println("Exception: an integer " + "cannot be divided by zero ");
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 8
Exception-Handling Overview
A template for a try-throw-catch block:
try {
Code to run;
A statement or a method that may throw an exception;
More code to run;
}
catch (type ex) {
code to process the exception;
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 9
Exception-Handling Overview
The try block contains the code that is executed in
normal circumstances.
The execution of a throw statement is called
throwing an exception.
When an exception is thrown, the normal
execution is interrupted.
The code in the catch block is executed next to
handle the exception.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 10
Handling InputMismatchException
InputMismatchExceptionDemo
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 11
import java.util.*; Example
public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println( "The number entered is " + number);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine(); // discard input
}
} while (continueInput);
}
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 12
Exception Types
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Error VirtualMachineError
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 13
System Errors
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 14
Exceptions
Exception describes errors
caused by your program ClassNotFoundException
and external ArithmeticException
circumstances. These IOException
errors can be caught and Exception NullPointerException
handled by your program.
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Error VirtualMachineError
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 15
Runtime Exceptions
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 16
Checked Exceptions vs. Unchecked
Exceptions
RuntimeException, Error and their
subclasses are known as unchecked
exceptions.
All other exceptions are known as checked
exceptions, meaning that the compiler
forces the programmer to check and deal
with the exceptions.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 17
Unchecked Exceptions
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 18
Unchecked Exceptions
In most cases, unchecked exceptions reflect programming
logic errors that are not recoverable.
For example:
– A NullPointerException is thrown if you access an object through
a reference variable before an object is assigned to it;
– An IndexOutOfBoundsException is thrown if you access an
element in an array outside the bounds of the array.
– These are the logic errors that should be corrected in the program.
Unchecked exceptions can occur anywhere in the program.
To avoid cumbersome overuse of try-catch blocks, Java
does not mandate you to write code to catch unchecked
exceptions.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 19
Declaring Exceptions
Every method must state the types of checked
exceptions it might throw. This is known as
declaring exceptions.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 20
Declaring, Throwing, and
Catching Exceptions
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 21
Throwing Exceptions
When the program detects an error, the program
can create an instance of an appropriate
exception type and throw it. This is known as
throwing an exception.
Here is an example,
IllegalArgumentException ex =
new IllegalArgumentException("Wrong Argument");
throw ex;
Or
throw new IllegalArgumentException("Wrong Argument");
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 22
Throwing Exceptions Example
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 23
Catching Exceptions
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 24
Catching Exceptions
main method { method1 { method2 { An exception
... ... ... is thrown in
try { try { try { method3
... ... ...
invoke method1; invoke method2; invoke method3;
statement1; statement3; statement5;
} } }
catch (Exception1 ex1) { catch (Exception2 ex2) { catch (Exception3 ex3) {
Process ex1; Process ex2; Process ex3;
} } }
statement2; statement4; statement6;
} } }
Call Stack
method3
method2 method2
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 25
Catching Exceptions
The order in which exceptions are specified
in catch blocks is important.
A compile error will result if a catch block
for a superclass type appears before a catch
block for a subclass type.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 26
Catching Exceptions
try { try {
… …
} }
catch (Exception ex) { catch (RuntimeException ex) {
… …
} }
catch (RuntimeException ex) { catch (Exception ex) {
… …
} }
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 27
Catch or Declare Checked Exceptions
Suppose p2 is defined as follows:
...
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 28
Catch or Declare Checked Exceptions
Java forces you to deal with checked exceptions. If a method declares a
checked exception (i.e., an exception other than Error or
RuntimeException), you must invoke it in a try-catch block or declare to
throw the exception in the calling method. For example, suppose that
method p1 invokes method p2 and p2 may throw a checked exception (e.g.,
IOException), you have to write the code as shown in (a) or (b).
(a) (b)
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 29
Example: Declaring, Throwing, and
Catching Exceptions
Objective: This example demonstrates declaring,
throwing, and catching exceptions by modifying
the setRadius method in the Circle class defined
in Chapter 9. The new setRadius method throws
an exception if radius is negative.
CircleWithException
TestCircleWithException
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 30
public class CircleWithException {
private double radius; Program
public CircleWithException(double newRadius) { Segment
setRadius(newRadius);
numberOfObjects++;
}
……
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 31
public class TestCircleWithException {
public static void main(String[] args) {
try {
CircleWithException c1 = new CircleWithException(5);
CircleWithException c2 = new CircleWithException(-5);
CircleWithException c3 = new CircleWithException(0);
}
catch (IllegalArgumentException ex) {
System.out.println(ex);
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 32
Getting Information from Exceptions
An exception object contains valuable
information about the exception.
The java.lang.Throwable class provides the
methods that can be used to get information
regarding the exception.
– Example: The printStackTrace() method prints
the exception and its call stack trace
information on the console.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 33
public class TestException {
public static void main(String[] args) {
try {
System.out.println(sum(new int[ ] {1, 2, 3, 4, 5}));
}
catch (Exception ex) {
ex.printStackTrace(); java.lang.ArrayIndexOutOfBoundsException: 5 at
TestException.sum(TestException.java:14) at
} TestException.main(TestException.java:4)
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 34
Rethrowing Exceptions
Java allows an exception handler to rethrow the exception
if the handler cannot process the exception.
try {
statements;
}
catch(TheException ex) {
perform operations before exits;
throw ex;
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 35
The finally Clause
try {
Occasionally, you statements;
may want some code }
to be executed catch(TheException ex)
regardless of whether {
handling ex;
an exception occurs }
or is caught. finally {
finalStatements;
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 36
The finally Clause
The code in the finally block is executed under all
circumstances.
– The catch block may be omitted when the finally block
is used, i.e., just try and finally blocks, no catch block.
The finally block executes even if there is a return
statement prior to reaching the block.
A common use of the finally clause is in I/O
programming. For example, to ensure that a file is
closed under all circumstances, you may place a
file closing statement in the finally block.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 37
Trace a Program Execution
Suppose no
exceptions in the
statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 38
Trace a Program Execution
The final block is
try { always executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 39
Trace a Program Execution
Next statement in the
try { method is executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 40
Trace a Program Execution
try { Suppose an exception
statement1; of type Exception1 is
statement2; thrown in statement2
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 41
Trace a Program Execution
try { The exception is
statement1; handled.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 42
Trace a Program Execution
try { The final block is
statement1; always executed.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 43
Trace a Program Execution
try { The next statement in
statement1; the method is now
statement2; executed.
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 44
Trace a Program Execution
try {
statement1; statement2 throws an
statement2; exception of type
statement3;
}
Exception2.
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 45
Trace a Program Execution
try {
statement1; Handling exception
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 46
Trace a Program Execution
try {
statement1; Execute the final block
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 47
Trace a Program Execution
try {
statement1; Rethrow the exception
statement2; and control is
statement3;
}
transferred to the caller
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 48
Cautions When Using Exceptions
Exception handling separates error-handling code from
normal programming tasks, thus making programs
easier to read and to modify.
Be aware, however, that exception handling usually
requires more time and resources because it requires
instantiating a new exception object, rolling back the
call stack, and propagating the errors to the calling
methods.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 49
When to Throw Exceptions
An exception occurs in a method. If you want
the exception to be processed by its caller, you
should create an exception object and throw it.
If you can handle the exception in the method
where it occurs, there is no need to throw it.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 50
When to Use Exceptions
When should you use the try-catch block in the code?
You should use it to deal with unexpected error
conditions. Do not use it to deal with simple, expected
situations. For example, the following code
try {
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 51
When to Use Exceptions
is better to be replaced by
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 52
Chained Exceptions
Sometimes, you may need to throw a new
exception (with additional information)
along with the original exception.
This is called chained exception.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 53
1 public class ChainedExceptionDemo {
2 public static void main(String[] args) {
3 try {
4 method1();
5 }
6 catch (Exception ex) {
7 ex.printStackTrace();
8 }
9 }
10
11 public static void method1() throws Exception {
12 try {
13 method2();
14 }
15 catch (Exception ex) {
16 throw new Exception("New info from method1", ex);
17 }
18 }
19 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 54
20 public static void method2() throws Exception {
21 throw new Exception("New info from method2");
22 }
23 }
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 55
Defining Custom Exception Classes
Java provides quite a few exception classes. Use them
whenever possible.
Define custom exception classes if the predefined
classes are not sufficient.
Define custom exception classes by extending
Exception or a subclass of Exception.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 56
Custom Exception Class Example
In Listing 13.8, the setRadius method throws an exception if the
radius is negative. Suppose you wish to pass the radius to the
handler, you have to create a custom exception class.
InvalidRadiusException
CircleWithRadiusException
TestCircleWithRadiusException
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 57
public class InvalidRadiusException extends Exception {
private double radius;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 58
In the Circle class
Program
/** Set a new radius */ segment
public void setRadius(double newRadius)
throws InvalidRadiusException {
if (newRadius >= 0)
radius = newRadius;
else
throw new InvalidRadiusException(newRadius);
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 59
In the Circle class
Program
/** Construct a circle with radius 1 */ segment
public Circle() throws InvalidRadiusException {
this(1.0);
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 60
public class TestCircle {
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 61
The File Class
The filename is a string. The File class is a wrapper
class for the file name and its directory path.
The File class contains the methods for obtaining the
properties of a file/directory and for renaming and
deleting a file/directory.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 62
Obtaining file properties and manipulating file
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 63
Problem: Explore File Properties
Objective: Write a program that demonstrates how to
create files in a platform-independent way and use the
methods in the File class to obtain their properties. The
following figures show a sample run of the program on
Windows and on Unix.
TestFileClass
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 64
public class TestFileClass {
public static void main(String[] args) {
java.io.File file = new java.io.File("image/us.gif");
System.out.println("Does it exist? " + file.exists());
System.out.println("The file has " + file.length() + " bytes");
System.out.println("Can it be read? " + file.canRead());
System.out.println("Can it be written? " + file.canWrite());
System.out.println("Is it a directory? " + file.isDirectory());
System.out.println("Is it a file? " + file.isFile());
System.out.println("Is it absolute? " + file.isAbsolute());
System.out.println("Is it hidden? " + file.isHidden());
System.out.println("Absolute path is " +
file.getAbsolutePath());
System.out.println("Last modified on " + new java.util.Date(file.lastModified()));
}
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 65
Text I/O
A File object encapsulates the properties of a file or a
path, but does not contain the methods for
reading/writing data from/to a file.
In order to perform I/O, you need to create objects using
appropriate Java I/O classes.
– To write data to a file, use the PrintWriter class.
– To read data from a file, use the Scanner class
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 66
Writing Data Using PrintWriter
java.io.PrintWriter
+PrintWriter(filename: String) Creates a PrintWriter for the specified file.
+print(s: String): void Writes a string.
+print(c: char): void Writes a character.
+print(cArray: char[]): void Writes an array of character.
+print(i: int): void Writes an int value.
+print(l: long): void Writes a long value.
+print(f: float): void Writes a float value.
+print(d: double): void Writes a double value.
+print(b: boolean): void Writes a boolean value.
Also contains the overloaded A println method acts like a print method; additionally it
println methods. prints a line separator. The line separator string is defined
Also contains the overloaded by the system. It is \r\n on Windows and \n on Unix.
printf methods. The printf method was introduced in §4.6, “Formatting
Console Output and Strings.”
.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 67
public class WriteData {
public static void main(String[] args) throws java.io.IOException {
java.io.File file = new java.io.File("scores.txt");
if (file.exists()) {
System.out.println("File already exists");
System.exit(0); Invoking the PrinterWriter
} constructor may throw an
I/O exception.
// Create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 69
public class WriteDataWithAutoClose {
public static void main(String[] args) throws Exception {
java.io.File file = new java.io.File("scores.txt");
if (file.exists()) {
System.out.println("File already exists");
System.exit(0);
}
try (
// Create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
){
// Write formatted output to the file
output.print("John T Smith ");
output.println(90);
WriteDataWithAutoClose
output.print("Eric K Jones ");
output.println(85);
}
}
} 70
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved.
Reading Data Using Scanner
java.util.Scanner
+Scanner(source: File) Creates a Scanner object to read data from the specified file.
+Scanner(source: String) Creates a Scanner object to read data from the specified string.
+close() Closes this scanner.
+hasNext(): boolean Returns true if this scanner has another token in its input.
+next(): String Returns next token as a string.
+nextByte(): byte Returns next token as a byte.
+nextShort(): short Returns next token as a short.
+nextInt(): int Returns next token as an int.
+nextLong(): long Returns next token as a long.
+nextFloat(): float Returns next token as a float.
+nextDouble(): double Returns next token as a double.
+useDelimiter(pattern: String): Sets this scanner’s delimiting pattern.
Scanner
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 71
import java.util.Scanner;
while (input.hasNext()) {
String firstName = input.next();
String mi = input.next(); ReadData
String lastName = input.next();
int score = input.nextInt();
System.out.println(firstName + " " + mi + " " + lastName + " " + score);
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 72
Reading Data Using Scanner
The token-based input methods nextByte(),
nextShort(), nextInt(), nextLong(), nextFloat(),
nextDouble(), and next() read input separately by
delimiters.
– By default, the delimiters are whitespace characters.
– You can use the useDelimiter(String regex) method to
set a new pattern for delimiters.
The nextLine() method reads a line ending with a
line separator.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 73
Reading Data Using Scanner
The token-based input method does not
read the delimiter after the token. If the
nextLine() method is invoked after a token-
based input method, this method reads
characters that starts from this delimiter
and ends with the line separator.
– The line separator is read, but it is not part of
the string returned by nextLine().
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 74
Reading Data Using Scanner
Example: Suppose a text file named test.txt
contains 34 567.
Scanner input = new Scanner(new File("test.txt"));
int intValue = input.nextInt(); // reads 34
String line = input.nextLine(); // reads a blank and 567
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 75
Problem: Replacing Text
Write a class named ReplaceText that replaces a string in a text
file with a new string. The filename and strings are passed as
command-line arguments as follows:
java ReplaceText sourceFile targetFile oldString newString
For example, invoking
java ReplaceText FormatString.java t.txt StringBuilder StringBuffer
replaces all the occurrences of StringBuilder by StringBuffer in
FormatString.java and saves the new file in t.txt.
ReplaceText
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 76
import java.io.*;
import java.util.*;
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 77
// Check if target file exists
File targetFile = new File(args[1]);
if (targetFile.exists()) {
System.out.println("Target file " + args[1] + " already exists");
System.exit(3);
}
try (
// Create input and output files
Scanner input = new Scanner(sourceFile);
PrintWriter output = new PrintWriter(targetFile);
){
while (input.hasNext()) {
String s1 = input.nextLine();
String s2 = s1.replaceAll(args[2], args[3]);
output.println(s2);
}
}
}
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 78
Reading Data from the Web
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 79
Reading Data from the Web
URL url = new URL("www.google.com/index.html");
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 80
import java.util.Scanner;
try {
java.net.URL url = new java.net.URL(URLString);
int count = 0;
Scanner input = new Scanner(url.openStream());
while (input.hasNext()) {
String line = input.nextLine();
count += line.length();
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 81
catch (java.net.MalformedURLException ex) {
System.out.println("Invalid URL");
}
catch (java.io.IOException ex) {
System.out.println("IO Errors: no such file");
}
}
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All
rights reserved. 82