Unit-4 Java
Unit-4 Java
HANDLING &
INPUT AND
OUTPUT
UNIT 4
EXCEPTION HANDLING:
EXCEPTION HANDLING
FUNDAMENTALS; EXCEPTION
TYPES; UNCAUGHT
EXCEPTIONS; USING TRY AND
CATCH; MULTIPLE CATCH
CLAUSES; NESTED TRY
STATEMENTS; THROW;
THROWS; FINALLY; JAVA’S
BUILT-IN EXCEPTIONS;
INPUT/OUTPUT: JAVA I/O
CLASSES AND INTERFACES;
FILE; THE STREAM CLASSES;
THE BYTE STREAMS;
CHARACTER STREAMS;
EXCEPTION-HANDLING FUNDAMENTALS (CHAPTER 10)
• A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of
code.
• When an exceptional condition arises, an object representing that exception is created and thrown in the method that
caused the error.
• That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is
caught and processed
• Exceptions can be generated by the Java run-time system, or they can be manually generated by your code.
• Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the
constraints of the Java execution environment.
EXCEPTION-HANDLING KEYWORDS
• Java exception handling is managed via five keywords: try, catch, throw, throws, and finally
• Program statements that you want to monitor for exceptions are contained within a try block.
• If an exception occurs within the try block, it is thrown.
• Your code can catch this exception (using catch) and handle it in some rational manner.
• System-generated exceptions are automatically thrown by the Java runtime system.
• To manually throw an exception, use the keyword throw.
• Any exception that is thrown out of a method must be specified as such by a throws clause.
• Any code that absolutely must be executed after a try block completes is put in a finally block.
EXCEPTION-HANDLING GENERAL FORMAT
// Demonstrate System.out.write().
class WriteDemo {
public static void main(String args[])
throws IOException { int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
THE PRINTWRITER CLASS
Although using System.out to write to the console is acceptable, its use is probably best for debugging purposes or for
sampleprograms, such as those found in this book. For realworld programs, the recommended method of writing to the
console when using Java is through a PrintWriter stream. PrintWriter is one of the character-based classes. Using a character-
based class for console output makes internationalizing your program easier. PrintWriter defines several constructors. The
one we will use is shown here:
PrintWriter(OutputStream outputStream, boolean flushingOn)
Here, outputStream is an object of type OutputStream, and flushingOn controls whether Java flushes the output stream every
time a println( ) method (among others) is called. If flushingOn is true, flushing automatically takes place. If false, flushing is
not automatic. To write to the console by using a PrintWriter, specify System.out for the output stream and automatic flushing.
For example, this line of code creates a PrintWriter that is connected to console output: PrintWriter pw = new
PrintWriter(System.out, true); The following application illustrates using a PrintWriter to handle console output:
// Demonstrate PrintWriter
import java.io.*; The output from this program is shown here:
public class This is a string
PrintWriterDemo { -7
public static void 4.5E-7
main(String args[]) {
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("This is a string");
int i = -7;
pw.println(i);
double d = 4.5e-7;
READING AND WRITING FILES
Java provides a number of classes and methods that allow you to read and write files. Two of the most often-used stream classes
are FileInputStream and FileOutputStream, which create byte streams linked to files. To open a file, you simply create an
object of one of these classes, specifying the name of the file as an argument to the constructor. Although both classes support
additional constructors, the following are the forms that we will be using:
Here, fileName specifies the name of the file that you want to open. When you create an input stream, if the file does not exist,
then FileNotFoundException is thrown. For output streams, if the file cannot be opened or created, then FileNotFoundException
is thrown. FileNotFoundException is a subclass of IOException. When an output file is opened, any preexisting file by the
same name is destroyed.
When you are done with a file, you must close it. This is done by calling the close( ) method, which is implemented by
both FileInputStream and FileOutputStream. It is shown here:
Closing a file releases the system resources allocated to the file, allowing them to be used by another file. Failure to close a
file can result in “memory leaks” because of unused resources remaining allocated.
READING AND WRITING FILES
To read from a file, you can use a version of read( ) that is defined within FileInputStream.
The one that we will use is shown here:
int read( ) throws IOException
Each time that it is called, it reads a single byte from the file and returns the byte as an integer value. read( ) returns –1 when the
end of the file is encountered. It can throw an IOException. The following program uses read( ) to input and display the
contents of a file that contains ASCII text. The name of the file is specified as a command-line argument.
import java.io.*;
class ShowFile { // At this point, the file is open and can be read.
public static void main(String args[]) // The following reads characters until EOF is encountered.
{ try {
int i; do {
FileInputStream fin; i = fin.read();
// First, confirm that a filename has been specified. if(i != -1) System.out.print((char) i);
if(args.length != 1) { } while(i != -1);
System.out.println("Usage: ShowFile filename"); } catch(IOException e)
return; { System.out.println("Error Reading
} File");
// Attempt to open the file. }
try { // Close the file.
fin = new try
FileInputStream(args[0]); { fin.close();
} catch(FileNotFoundException e) } catch(IOException e)
{ System.out.println("Cannot Open { System.out.println("Error Closing
File"); return; } File");
READING AND WRITING FILES
To write to a file, you can use the write( ) method defined by FileOutputStream. Its simplest form is shown here:
void write(int byteval) throws IOException
This method writes the byte specified by byteval to the file. Although byteval is declared as an integer, only the low-order eight
bits are written to the file. If an error occurs during writing, an IOException is thrown. The next example uses write( ) to copy
a file.
import java.io.*; class do {
CopyFile { i = fin.read();
public static void main(String args[]) throws if(i != -1) fout.write(i);
IOException } while(i != -1);
{ } catch(IOException e)
int i; { System.out.println("I/O Error: " +
FileInputStream fin = null; e);
FileOutputStream fout = null; } finally {
// First, confirm that both files have been specified. try {
if(args.length != 2) { if(fin !=
System.out.println("Usage: CopyFile from to"); return; null)
} fin.close()
// Copy a File. try { ;
// Attempt to open the } catch(IOException e2)
files. { System.out.println("Error Closing Input
fin = new FileInputStream(D:\\ File");
Girish\\
EclipseWorkspace\\
}
AUTOMATICALLY CLOSING A FILE
Automatic resource management is based on an expanded form of the try statement.
Here is its general form:
try (resource-specification) {
// use the resource
}
Here, resource-specification is a statement that declares and initializes a resource, such as a file stream. It consists of a
variable declaration in which the variable is initialized with a reference to the object being managed. When the try block ends,
the resource is automatically released. In the case of a file, this means that the file is automatically closed. (Thus, there is no
need to call close( ) explicitly.) Of course, this form of try can also include catch and finally clauses.
import java.io.*;
class ShowFile {
public static void main(String args[])
try(FileInputStream fin = new FileInputStream(args[0])) {
{ do {
int i; i = fin.read();
// First, confirm that a filename has been specified. if(i != -1) System.out.print((char) i);
if(args.length != 1) { } while(i != -1);
System.out.println("Usage: ShowFile filename");
return;
} } catch(FileNotFoundException e)
// The following code uses a try-with- { System.out.println("File Not
resources statement to open Found.");
// a file and then automatically close it when the try } catch(IOException e) {
block is left.
System.out.println("An I/O Error