0% found this document useful (0 votes)
34 views40 pages

Unit-4 Java

Uploaded by

lavanyasujat
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
34 views40 pages

Unit-4 Java

Uploaded by

lavanyasujat
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 40

EXCEPTION

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

This is the general form of an exception-handling


block: try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block
of code
to be
execute
d after
try
block
EXCEPTION TYPES
• All exception types are subclasses of the built-in class Throwable.
• Thus, Throwable is at the top of the exception class hierarchy. Immediately below Throwable are two subclasses
that partition exceptions into two distinct branches.
• One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch.
This is also the class that you will subclass to create your own custom exception types. There is an important
subclass of Exception, called RuntimeException
• The other branch is topped by Error, which defines exceptions that are not expected to be caught under normal
circumstances by your program.
• Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time
environment, itself. Stack overflow is an example of such an error.
• Type Error, are typically created in response to catastrophic failures that cannot usually be handled by your
program.
EXCEPTION TYPES DIAGRAM
UNCAUGHT EXCEPTIONS
Here is the exception generated when this example is executed:
This small program includes an expression that java.lang.ArithmeticException: / by zero
intentionally causes a divide-by-zero error: at Exc0.main(Exc0.java:4)
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
When the Java run-time system detects the attempt to divide by
zero, it constructs a new exception object and then throws this
exception. This causes the execution of Exc0 to stop,
because once an exception has been thrown, it must be caught
by an exception handler and dealt with immediately. In this
example, we haven’t supplied any exception handlers of our
own, so the exception is caught by the default handler
provided by the Java run-time system
USING TRY AND CATCH
Although the default exception handler provided by the Java run-time system is useful for debugging, you will
usually want to handle an exception yourself. Doing so provides two benefits. First, it allows you to fix the error.
Second, it prevents the program from automatically terminating.
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of
code. d = 0;
a = 42 / d;
System.out.println("This will
not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero
error System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
This program generates the following
output: Division by zero.
JAVA’S BUILT-IN EXCEPTIONS
MULTIPLE CATCH CLAUSES
In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, you
can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown,
each catch statement is inspected in order, and the first one whose type matches that of the exception is executed.
After one catch statement executes, the others are bypassed, and execution continues after the try /catch block. The
following example traps two different exception types:
// Demonstrate multiple catch statements.
class MultipleCatches {
Here is the output generated by running it both ways:
public static void main(String args[]) {
C:\>java MultipleCatches
try {
a=0
int a = args.length;
Divide by 0: java.lang.ArithmeticException: / by zero
System.out.println("a = " + a);
After try/catch blocks.
int b = 42 / a;
C:\>java MultipleCatches TestArg
int c[] = { 1 };
a=1
c[42] = 99;
Array index oob:
} catch(ArithmeticException e)
java.lang.ArrayIndexOutOfBoundsException:42
{ System.out.println("Divide by 0: " +
After try/catch blocks.
e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
NESTED TRY STATEMENTS
The try statement can be nested. That is, a try statement can be inside the block of another try. Each time a try
statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch
handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a
match.This continues until one of the catch statements succeeds, or until all of the nested try
statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception. Here
is an example that uses nested try statements:
NESTED TRY EXAMPLE
// An example of nested try statements. /* If two command-line args are used,
class NestTry { then generate an out-of-bounds exception.
public static void main(String args[]) { */ if(a==2) {
try { int c[] = { 1 };
int a = args.length; c[42] = 99; // generate an out-of-bounds
/* If no command-line args are present, exception
the following statement will generate }
a divide-by-zero exception. */ } catch(ArrayIndexOutOfBoundsException e)
int b = 42 / a; { System.out.println("Array index out-of-bounds: " +
System.out.println("a = " + a); e);
try { // nested try block /* If one }
command-line arg is used, then a } catch(ArithmeticException e)
divide-by-zero exception will be { System.out.println("Divide by 0: " + e);
generated by the following code. */
if(a==1) a = a/(a-a); // division by zero } }}
C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a=1
Divide by 0: java.lang.ArithmeticException: / by zero
THROW
So far, we have only been catching exceptions that are thrown by the Java run-time system. However, it is possible
for your program to throw an exception explicitly, using the throw statement. The general form of throw is shown
here:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Primitive types, such as
int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. There are
two ways you can obtain a Throwable object: using a parameter in a catch clause or creating one with the new
operator.
The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.
The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception. If
it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is
inspected, and so on. If no matching catch is found, then the default exception handler halts the program and
prints the stack trace.
EXAMPLE FOR THROW
Here is the resulting output:
// Demonstrate throw. Caught inside demoproc.
class ThrowDemo Recaught: java.lang.NullPointerException: demo
{ static void demoproc() The program also illustrates how to create one of Java’s
{ try { standard exception objects.
throw new throw new NullPointerException("demo");
NullPointerException("
demo");
} catch(NullPointerException e)
{ System.out.println("Caught inside
demoproc."); throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e)
{ System.out.println("Recaught: " +
e);
THROWS
If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of
the method can guard themselves against that exception. We do this by including a throws clause in the method’s
declaration. A throws clause lists the types of exceptions that a method might throw. This is necessary for all
exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a
method can throw must be declared in the throws clause. If they are not, a compile-time error will result.
This is the general form of a method declaration that includes a throws
clause: type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method
can throw
// This program contains an error and will not compile.
class ThrowsDemo {
static void throwOne()
{ System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne(); } }
EXAMPLE FOR THROWS
// This is now correct.
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e)
{ System.out.println("Caught " +
e);
}
}
}
Here is the output generated by running this example
program: inside throwOne
caught java.lang.IllegalAccessException: demo
FINALLY
finally creates a block of code that will be executed after a try /catch block has completed and before the code
following the try/catch block. The finally block will execute whether an exception is thrown or not. If an exception is
thrown, the finally block will execute even if no catch statement matches the exception. Any time a method is about to
return to the caller from inside a try/catch block, via an uncaught exception or an explicit return
statement, the finally clause is also executed just before the method returns. This can be useful for closing file
handles and freeing up any other resources that might have been allocated at the beginning of a method with the
intent of disposing of them before returning. The finally clause is optional. However, each try statement requires at
least one catch or a finally clause.
// Execute a try block normally.
// Demonstrate finally. // Return from within a try block.
static void procC() {
class FinallyDemo { static void procB() {
try {
// Throw an exception out of the method. try {
System.out.println("
static void procA() { System.out.println("inside procB");
inside procC");
try { return;
} finally
System.out.println("inside procA"); } finally
{ System.out.println("procC's
throw new RuntimeException("demo"); { System.out.println("procB's
finally");
} finally finally");
}
{ System.out.println("procA's }
}
finally"); }
}
}
EXAMPLE FOR FINALLY
public static void main(String args[]) { Here is the output generated by the preceding
try { program: inside procA
procA(); procA's finally
} catch (Exception e) Exception caught
{ System.out.println("Exception inside procB
caught"); procB's finally
} inside procC
procB(); procC's finally
procC();
}
}
CREATING YOUR OWN EXCEPTION SUBCLASSES
Although Java’s built-in exceptions handle most common errors, you will probably want to create your own exception
types to handle situations specific to your applications. This is quite easy to do: just define a subclass of Exception
(which is, of course, a subclass of Throwable). Your subclasses don’t need to actually implement anything—it is their
existence in the type system that allows you to use them as exceptions.
The Exception class does not define any methods of its own. It does, of course, inherit those methods provided by
Throwable. Thus, all exceptions, including those that you create, have the methods defined by Throwable available to
them. They are shown in Table below. You may also wish to override one or more of these methods in exception classes
that you create.
Exception defines four public constructors. Two support chained exceptions, The other two are shown here:
Exception( )
Exception(String msg)
The first form creates an exception that has no description. The second form lets you specify a description of
the exception.
TABLE- METHODS OF EXCEPTION
TABLE- METHODS OF EXCEPTION – CONT’D…
USER DEFINED EXCEPTION
class ExceptionDemo {
// This program creates a custom exception
static void compute(int a) throws MyException {
type. class MyException extends Exception {
System.out.println("Called compute(" + a +
private int detail;
")"); if(a > 10)
MyException(int a) {
throw new MyException(a);
detail = a;
System.out.println("Normal exit");
}
}
public String
public static void main(String args[]) {
toString() {
try {
return
compute(1);
"MyException[" +
compute(20);
detail + "]";
} catch (MyException e)
} Here is the result:
{ System.out.println("Caught " +
} Called compute(1)
e);
Normal exit
}
Called compute(20)
}
Caught MyException[20]
}
CHAINED EXCEPTIONS
Beginning with JDK 1.4, a feature was incorporated into the exception subsystem: chained exceptions. The chained
exception feature allows you to associate another exception with an exception. This second exception describes the cause
of the first exception. For example, imagine a situation in which a method throws an ArithmeticException because of an
attempt to divide by zero. However, the actual cause of the problem was that an I/O error occurred,
which caused the divisor to be set improperly. Although the method must certainly throw an ArithmeticException, since
that is the error that occurred, you might also want to let the calling code know that the underlying cause was an I/O
error.

The chained exception methods supported by Throwable are,


To allow chained exceptions, two constructors and two Throwable getCause( )
methods were added to Throwable. Throwable initCause(Throwable causeExc)
The constructors are shown here:
Throwable(Throwable causeExc)
Throwable(String msg, Throwable causeExc)
CHAINED EXCEPTIONS EXAMPLEpublic static void main(String args[]) {
// Demonstrate exception chaining. try
class ChainExcDemo { { demopro
static void demoproc() { c();
// create an exception }
NullPointerException e = catch(NullP
new ointerExcep
NullPointerException("to tion e) {
p layer"); // display top level exception
// add a cause System.out.println("Caught: " + e);
e.initCause(new ArithmeticException("cause")); // display cause exception
throw e; System.out.println("Original cause: " + e.getCause());
} }
}
The output from the program is shown here:
}
Caught: java.lang.NullPointerException: top layer
Original cause: java.lang.ArithmeticException:
cause
I/O Classes(CHAPTER 13)
The io package supports Java’s basic I/O (input/output) system, including file I/O. Support for both I/O and applets comes
from Java’s core API libraries, not from language keywords.
I/O Basics:
Although we have not used more i/o functions except print and println functions, Java does provide strong, flexible
support for I/O as it relates to files and networks. Java’s I/O system is cohesive and consistent. In fact, once you
understand its fundamentals, the rest of the I/O system is easy to master. A general overview of I/O is discussed
here.
Streams:
Java programs perform I/O through streams. A stream is an abstraction that either produces or consumes information. A
stream is linked to a physical device by the Java I/O system. All streams behave in the same manner, even if the actual
physical devices to which they are linked differ. Thus, the same I/O classes and methods can be applied to different types
of devices. This means that an input stream can abstract many different kinds of input: from a disk file, a keyboard, or a
network socket. Likewise, an output stream may refer to the console, a disk file, or a network connection
DIFFERENCE BETWEEN SCANNER AND BUFFEREDREADER CLASS
Sr. Key Scanner Class BufferReader Class
No.

Synchronou Scanner is not syncronous in BufferReader is syncronous in


1 s nature and should be used only in nature. During multithreading
single threaded case. environment, BufferReader
should be used.
Buffer Scanner has little buffer of 1 KB BufferReader has large buffer of
2
Memor char buffer. 8KB byte Buffer as compared to
y Scanner.
Processin Scanner is bit slower as it need to BufferReader is faster than Scanner
3
g Speed parse data as well. as it only reads a character
stream.
Methods Scanner has methods like BufferReader has methods
4
nextInt(), nextShort() etc. like parseInt(),
parseShort() etc.
Read Line Scanner has method nextLine() to BufferReader has method
5
read a line. readLine() to read a line.
BYTE STREAMS AND
CHARACTER STREAMS
Java defines two types of streams: byte and
character. Byte streams provide a convenient means
for handling input and output of bytes. Byte streams
are used, for example, when reading or writing
binary data. Character streams provide a convenient
means for handling input and output of characters.
They use Unicode and, therefore, can be
internationalized. Also, in some cases, character
streams are more efficient than byte streams.

The Byte Stream Classes:


Byte streams are defined by using two class
hierarchies. At the top are two abstract classes:
InputStream and OutputStream. Each of these
abstract classes has several concrete subclasses that
handle the differences among various devices, such
as disk files, network connections, and even memory
buffers. The byte stream classes in java.io are shown
in Table below
The abstract classes InputStream and OutputStream
define several key methods that the other stream
classes implement. Two of the most important are
read( ) and write( ), which, respectively, read and
write bytes of data. Each has a form that is abstract
and must be overridden by derived stream classes.
The Character Stream Classes
Character streams are defined by using two class hierarchies. At the top are two abstract classes: Reader and Writer. These
abstract classes handle Unicode character streams. Java has several concrete subclasses of each of these. The character stream
classes in java.io are shown in Table below. The abstract classes Reader and Writer define several key methods that the other
stream classes implement. Two of the most important methods are read( ) and write( ), which read and write characters of data,
respectively. Each has a form that is abstract and must be overridden by derived stream classes.
THE PREDEFINED STREAMS
As we know, all Java programs automatically import the java.lang package. This package defines a class called System, which
encapsulates several aspects of the run-time environment. For example, using some of its methods, you can obtain the current
time and the settings of various properties associated with the system. System also contains three predefined stream variables:
in, out, and err. These fields are declared as public, static, and final within System. This means that they can be used by any
other part of your program and without reference to a specific System object.
System.out refers to the standard output stream. By default, this is the console. System.in refers to standard input, which is the
keyboard by default. System.err refers to the standard error stream, which also is the console by default. However, these streams
may be redirected to any compatible I/O device. System.in is an object of type InputStream; System.out and System.err are
objects of type PrintStream. These are byte streams, even though they are typically used to read and write characters from and to
the console. We can wrap these within character-based streams, if desired.
READING CONSOLE INPUT
In Java 1.0, the only way to perform console input was to use a byte stream. Today, using a byte stream to read console
input is still acceptable. However, for commercial applications, the preferred method of reading console input is to use a
character-oriented stream. This makes your program easier to internationalize and maintain. In Java, console input is
accomplished by reading from System.in. To obtain a characterbased stream that is attached to the console, wrap System.in
in a BufferedReader object. BufferedReader supports a buffered input stream. A commonly used constructor is shown here:
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract
class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. To obtain an
InputStreamReader object that is linked to System.in, use the following constructor:
InputStreamReader(InputStream inputStream)
Because System.in refers to an object of type InputStream, it can be used for inputStream.Putting it all together, the
following line of code creates a BufferedReader that is connected to the keyboard:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
After this statement executes, br is a character-based stream that is linked to the console through System.in
READING CHARACTERS
To read a character from a BufferedReader, use read( ). The version of read( ) that we will be using is
int read( ) throws IOException
Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value. It returns –1 when
the end of the stream is encountered. As you can see, it can throw an IOException. The following program demonstrates read( )
by reading characters from the console until the user types a "q." Notice that any I/O exceptions that might be generated are
simply thrown out of main( ). Such an approach is common when reading from the console
// Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead { Here is a sample run:
public static void main(String args[]) throws IOException Enter characters, 'q' to quit.
{ 1
char c; 1
BufferedReader br = new 2
BufferedReader(new InputStreamReader(System.in)); 2
System.out.println("Enter characters, 'q' to quit."); q
// read characters
do { q
c = (char) br.read();
System.out.println(c);
} while(c != 'q’); } }
READING STRINGS
To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class. Its general
form is shown here:
String readLine( ) throws IOException
As you can see, it returns a String object. The following program demonstrates BufferedReader and the readLine( ) method;
the program reads and displays lines of text until you enter the word "stop“.

// Read a string from console using a BufferedReader.


Here is a sample run:
import java.io.*;
Enter lines of text.
class BRReadLines {
Enter 'stop' to
public static void main(String args[]) throws
quit. This is line
IOException
one.
{
This is line one.
// create a BufferedReader using System.in
This is line two.
BufferedReader br = new BufferedReader(new
This is line two
InputStreamReader(System.in));
Java makes working with strings easy.
String str;
Java makes working with strings
System.out.println("Enter lines of text.");
easy. Just create String objects.
System.out.println("Enter 'stop' to quit.");
Just create String objects.
do {
stop
str = br.readLine();
System.out.println(str);
} while(!
WRITING CONSOLE OUTPUT
Console output is most easily accomplished with print( ) and println( ), described earlier, which are used in most of the
examples in this book. These methods are defined by the class PrintStream (which is the type of object referenced by
System.out). Even though System.out is a byte stream, using it for simple program output is still acceptable. However,
a character-based alternative is also available. Because PrintStream is an output stream derived from OutputStream, it also
implements the low-level method write( ). Thus, write( ) can be used to write to the console. The simplest
form of write( ) defined by PrintStream is shown here:
void write(int byteval)
This method writes the byte specified by byteval. Although byteval is declared as an integer, only the low-order eight bits are
written. Here is a short example that uses write( ) to output the character "A" followed by a newline to the screen:

// 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:

FileInputStream(String fileName) throws FileNotFoundException


FileOutputStream(String fileName) throws FileNotFoundException

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:

void close( ) throws IOException

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

You might also like