Unit-2 Exception Handling and IO Streams
Unit-2 Exception Handling and IO Streams
UNIT – 2
EXCEPTION HANDLING AND I/O EXCEPTIONS
Types of Errors:
Errors may broadly be classified in to two categories.
Compile time error
Run time error
{
Runer r = new Runer();
int result=r.divi(5,0);
System.out.println(result);
}
}
When we compile the above program, then it will create the .class file as the compilation
is successful. The compiler will not display any error message as there is no syntax error
in the code.
When we try to run the program then it will display the error condition which causes the
program to stop after displaying the appropriate message.
Exceptions : Exception is a condition that is caused by run time error in the program.
Or
An exception is an event that occurs during the execution of a program that disrupts the
normal flow of execution or an abnormal condition that disrupts Normal program flow.
When the Java interpreter encounters an error such as dividing an integer by zero, it
creates an exception object and throws it (i.e., informs us that an error has occurred).
If the exception object is not caught and handled properly, the interpreter will display an
error message and will terminate the program.
If we want the program to continue with the execution of remaining code then we should try
to catch the exception object thrown by error condition and then display an error message
for taking corrective actions. This task is known as exception handling.
The purpose of exception handing mechanism is to provide a means to detect and report an
“exceptional circumstance” so that appropriate action can be taken.
The mechanism suggests incorporation of a separate error handling code that performs the
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
following tasks:
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information ( Catch the exception)
4. Take corrective actions (Handle the exception)
The error handling code basically consists of two segments , one to detect errors and to
throw exceptions and the other to catch exceptions and to take appropriate actions.
There are many cases where abnormal conditions happen during program execution,
such as:
Trying to access an out - of –bounds array elements.
The file we try to open may not exist.
The file we want to load may be missing or in the wrong format.
The other end of our network connection may be non –existence.
If these cases are not prevented or at least handled properly, either the program will
be aborted abruptly, or the incorrect results or status will be produced.
When an error occurs with in the java method, the method creates an exception
object and hands it off to the runtime system.
The exception object contains information about the exception including its type and
the state of the program when the error occurred. The runtime system is then
responsible for finding some code to handle the error.
In java creating an exception object and handling it to the runtime system is called
throwing an exception.
Exception is an object that is describes an exceptional ( i.e. error) condition that has
occurred in a piece of code at run time.
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
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
These exceptions are caused by user error, programmer error, and physical resources.Based
on these, the exceptions can be classified into three categories.
Checked exceptions − A checked exception is an exception that occurs at the
compile time, also called as compile time (static time) exceptions. These
exceptions cannot be ignored at the time of compilation. So, the programmer
should handle these exceptions.
Unchecked exceptions − An unchecked exception is an exception that occurs at
run time, also called as Runtime Exceptions. These include programming bugs,
such aslogic errors or improper use of an API. Runtime exceptions are ignored at
the time ofcompilation.
Errors − Errors are not exceptions, but problems may arise beyond the control of
theuser or the programmer. Errors are typically ignored in our code because we
can rarely do anything about an error. For example, if a stack overflow occurs, an
error will arise. They are also ignored at the time of compilation.
try
{
{
// block of code to be executed before try block ends
}
Exception hierarchy
The java.lang.Exception class is the base class for all exception classes.
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 we will subclass to create our
own custom exception types.
There is an important subclass of Exception, called RuntimeException. Exceptions of this
type are automatically defined for the programs that we write and include things such as
division by zero and invalid array indexing.
The other branch is topped by Error, which defines exceptions that are not expected to be
caught under normal circumstances by our 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.
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
Exceptions Methods
Method Description
public String getMessage() Returns a detailed message about the exception that
has occurred. This message is initialized in the
Throwable constructor.
public Throwable getCause() Returns the cause of the exception as represented by
aThrowable object.
public String toString() Returns the name of the class concatenated with the
re-sult of getMessage().
public void printStackTrace() Prints the result of toString() along with the stack trace
toSystem.err, the error output stream.
public StackTraceElement Returns an array containing each element on the stack
trace. The element at index 0 represents the top of the
[]getStackTrace()
call stack, and the last element in the array represents
themethod at the bottom of the call stack.
public Fills the stack trace of this Throwable object with the
current stack trace, adding to any previous information
Throwable
in the stack trace.
fillInStackTrace(
)
try
{
// block of code to monitor for errors
// the code you think can raise an exception
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
Java uses the keyword try to preface a block of a code that is likely to cause an error
condition and “throw” an exception. A catch block defined by the keyword catch “catches
“ the exception thrown by the try block and handles it appropriately.
The try block can have one more than one statement that could generate an exception. If nay
one statement generates an exception the remaining code in the block are skipped and
execution jumps to the catch block that is placed next to the try block.
The catch block can also have more than one statements that are necessary to process the
exception.
A catch statement involves declaring the type of exception that might be tried to catch.
If an exception occurs, then the catch block (or blocks) which follow the try block is
checked.
If the type of exception that occurred is listed in a catch block, the exception is passed to
the catch block similar to an argument that is passed into a method parameter.
To illustrate the try-catch blocks the following program is developed.
class Erex2
{
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
{
x= a/(b-c);
System.out.println(“x=”+x);
}
catch (ArithmeticException e)
{
System.out.println(“Division by zero.”);
}
y= a/(b+c);
system.out.println(“y=.”+y);
}
}
Output:
int i=0;
int n, count=0;
for( int j=0;j<args.length;j++)
{
try
{
n= Integer.parseInt(args[j]);
}
catch(NumberFormatException e)
{
i=i+1;
System.out.println("invalid number="+args[j]);
continue;
}
count=count+1;
}
System.out.println("valid number="+count);
System.out.println("Invalid number="+i);
}
}
try
int b = a[11]/0;
catch(ArithmeticException e)
System.out.println(e.getMessage());
catch(ArrayIndexOutOfBoundsException e)
System.out.println(e.getMessage());
catch(Exception e)
System.out.println(e.getMessage());
}.
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
While the multiple catch statements is used, it is important to remember that exception
subclasses must come before their super classes. A catch statement which uses a superclass
will catch exceptions of that type plus any of its subclasses. Thus, a subclass would never
be reached if it came after its superclass. And also, in Java, unreachable code is an error.
Forexample, consider the following program:
class MultiCatch_Example
{
public static void main(String args[])
{
try
{
int a,b;
a = args.length;
System.out.println(“a = “ + a);
b = 10 / a; //may cause division-by-zero
errorint arr[] = { 10,20 };
c[5] =100;
}
catch(Exception e)
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array index oob: “ + e);
}
System.out.println(“After try/catch blocks.”);
}
}
The exceptions such as ArithmeticException, and ArrayIndexOutOfBoundsException are
the subclasses of Exception class. The catch statement after the base class catch statement
israising the unreachable code exception.
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
System.out.println(“division”);
int a,b;
a=0;
b =10/a;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
try
{
int a[]=new
int[5];
a[6]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println(“other statement);
}
catch(Exception e)
{
System.out.println(“handeled”);}
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
System.out.println(“normal flow..”);
}
}
int a,b;
a=0;
b=10/a;
}
catch(ArithmeticException e)
{
System.out.println("Exception thrown :" + e);
}
finally
{
System.out.println("The finally block is executed");
}
}
}
Points to remember:
A catch clause cannot exist without a try statement.
It is not compulsory to have finally clauses whenever a try/catch block is present.
The try block cannot be present without either catch clause or finally clause.
Any code cannot be present in between the try, catch, finally blocks.
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
Throw keyword
The Java throw keyword is used to explicitly throw an exception. The general form of
throw is shown below:
throw ThrowableInstance;
or
throw new Throwable_subclass
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throw-
able.
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 to obtain a Throwable object:
1. using a parameter in a catch clause
2. creating one with the new operator.
}
}
public static void main(String args[])
{
System.out.println("Enter age");
Scanner s = new Scanner(System.in);
int age= s.nextInt();
try
{
validate(age);
}
catch(ArithmeticException e)
{
System.out.println("ReCaught ArithmeticExceptions.");
}
}
}
The flow of execution stops immediately after the throw statement and any subsequent
statements that 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 trans-ferred 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 printsthe stack trace.
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
If a method does not handle a checked exception, the method must be declared using
the throws keyword. The throws keyword appears at the end of a method’s signature.
The difference between throws and throw keywords is that, throws is used to postpone the
handling of a checked exception and throw is used to invoke an exception explicitly.
The following method declares that it throws a Remote Exception −
Example
import java.io.*;
public class throw_Example1
{
public void function(int a) throws RemoteException
{
// Method implementation
throw new
RemoteException();
BUILT-IN EXCEPTIONS
Built-in exceptions are the exceptions which are available in Java libraries. These excep-
tions are suitable to explain certain error situations. Below is the list of important built-in
exceptions in Java.
Exceptions Description
Arithmetic Exception It is thrown when an exceptional condition has oc-curred
in an arithmetic operation.
Array Index Out Of Bound It is thrown to indicate that an array has been accessedwith
Exception an illegal index. The index is either negative or greater than
or equal to the size of the array.
ClassNotFoundException This Exception is raised when we try to access a classwhose
definition is not found.
FileNotFoundException This Exception is raised when a file is not accessible
or does not open.
IOException It is thrown when an input-output operation failed or
interrupted.
InterruptedException It is thrown when a thread is waiting, sleeping, or do-ing
some processing, and it is interrupted.
NoSuchFieldException It is thrown when a class does not contain the field (or
variable) specified.
NoSuchMethodException It is thrown when accessing a method which is notfound.
}
catch(NumberFormatException e)
Java allows the user to create their own exception class which is derived from built-in
class Exception. The Exception class inherits all the methods from the class Throwable.
The Throwable class is the superclass of all errors and exceptions in the Java language. It
contains a snapshot of the execution stack of its thread at the time it was created. It can also
contain a message string that gives more information about the error.
The Exception class is defined in java.lang package.
User defined exception class must inherit Exception class.
The user defined exception can be thrown using throw keyword.
Syntax:
class User_defined_name extends Exception
{
………..
}
Some of the methods defined by Throwable are shown in below table.
Methods Description
Throwable fillInStackTrace( ) Fills in the execution stack trace and returns a
Throwable object.
String getLocalizedMessage() Returns a localized description of the exception.
void printStackTrace( ) Displays the stack trace.
String toString( ) Returns a String object containing a descriptionof the
Exception.
StackTraceElement[ Returns an array that contains the stack trace, oneelement at
]getStackTrace( ) a time, as an array of StackTraceEle- ment.
In the above example, a custom defined exception class MyException is created by inher-
iting it from Exception class. The toString() method is overridden to display the
customized method on catch. The MyException is raised using the throw keyword.
Example:
Program to create user defined exception that test for odd
numbers.import java.util.Scanner;
class OddNumberException extends Exception
{
OddNumberException() //default constructor
{
super(“Odd number exception”);
}
OddNumberException(String msg) //parameterized constructor
{
super(msg);
}
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
}
public class
UserdefinedExceptionDemo{
public static void main(String[]
args)
{
int num;
Scanner Sc = new Scanner(System.in); // create Scanner object to read
inputSystem.out.println(“Enter a number : “);
num = Integer.parseInt(Sc.nextLine());
try
{
if(num%2 != 0) // test for odd number
throw(new OddNumberException()); // raise the exception if number is
odd
else
System.out.println(num + “ is an even number”);
}
catch(OddNumberException Ex)
{
System.out.print(“\n\tError : “ + Ex.getMessage());
}
}
}
Sample Output1:
Enter a number : 11
Error : Odd number exception
Sample Output2:
10 is an even number
Odd Number Exception class is derived from the Exception class. To implement user
defined exception we need to throw an exception object explicitly. In the above example,
If the value of num variable is odd, then the throw keyword will raise the user defined
exceptionand the catch block will get execute.
CHAINED EXCEPTIONS
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
Chained Exceptions allows to relate one exception with another exception, i.e one ex-
ception describes cause of another exception. For example, consider a situation in which
a method throws an ArithmeticException because of an attempt to divide by zero but the
actualcause of exception was an I/O error which caused the divisor to be zero. The method
will throw only ArithmeticException to the caller. So the caller would not come to know
about theactual cause of exception. Chained Exception is used in such type of situations.
Throwable constructors that supports chained exceptions are:
1. Throwable(Throwable cause) :- Where cause is the exception that causes the
current
exception.
2. Throwable(String msg, Throwable cause) :- Where msg is the exception message
and
cause is the exception that causes the current exception.
Throwable methods that supports chained exceptions are:
1. getCause() method :- This method returns actual cause of an exception.
2. initCause(Throwable cause) method :- This method sets the cause for the calling
ex-ception.
Example:
import java.io.IOException;
public class
ChainedException
{
public static void divide(int a, int b)
{
if(b==0)
{
ArithmeticException ae = new ArithmeticException(“top layer”);
ae.initCause( new IOException(“cause”) );
throw ae;
}
else
{
System.out.println(a/b);
}
}
public static void main(String[] args)
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
{
try {
divide(5, 0);
}
catch(ArithmeticException ae) {
System.out.println( “caught : “ +ae);
System.out.println(“actual cause:
“+ae.getCause());
}
}
}
Sample Output:
caught : java.lang.ArithmeticException: top
layeractual cause: java.io.IOException: cause
Method Descriptio
n
boolean equals(Object obj) Returns true if the invoking StackTraceElement is the
same as the one passed in obj. Otherwise, it returns false.
String getClassName() Returns the class name of the execution point
String getFileName( ) Returns the filename of the execution point
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
INPUT/OUTPUT BASICS
Java I/O (Input and Output) is used to process the input and produce the output. Java uses
the concept of stream to make I/O operation fast. All the classes required for input and output
operations are declared in java.io package.
A stream can be defined as a sequence of data. The Input Stream is used to read data from
a source and the OutputStream is used for writing data to a destination.
InputStream class
InputStream class is an abstract class. It is the super class of all classes representing an
input stream of bytes.
The Input Strearn class is the superclass for all byte-oriented input stream classes.
All the methods of this class throw an IOException.
Being an abstract class, the InputStrearn class cannot be instantiated hence,
itssubclasses are used
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
Class Description
Buffered Input Stream Contains methods to read bytes from the buffer (memory area)
Byte Array Input Stream Contains methods to read bytes from a byte array
Data Input Stream Contains methods to read Java primitive data types
File Input Stream Contains methods to read bytes from a file
Filter Input Stream Contains methods to read bytes from other input streams which it uses
as its basic source of data
Object Input Stream Contains methods to read objects
Piped Input Stream Contains methods to read from a piped output stream. Apipe input
stream must be connected to a piped output stream
Sequence Input Stream Contains methods to concatenate multiple input streams and
then read from the combined stream
Method Description
public abstract int read() Reads the next byte of data from the input stream. It returns -1at
throws IOException the end of file.
public int available() Returns an estimate of the number of bytes that can be read
throws IOException from the current input stream.
public void close() Close the current input stream
throws IOException
Class Description
Buffered Output Stream Contains methods to write bytes into the buffer
Byte Array Output Stream Contains methods to write bytes into a byte array
Data Output Stream Contains methods to write Java primitive data types
File Output Stream Contains methods to write bytes to a file
Filter Output Stream Contains methods to write to other output streams
Object Output Stream Contains methods to write objects
Piped Output Stream Contains methods to write to a piped output stream
Print Stream Contains methods to print Java primitive data types
Method Description
public void write(int)throws Write a byte to the current output stream.
IO Exception
public void write(byte[]) Write an array of byte to the current output
throws IO Exception stream.
public void flush()throws Flushes the current output stream.
IO Exception
public void close()throws close the current output stream.
IO Exception
The character stream classes are also topped by two abstract classes Reader and Writer.
Method Description
int read() returns the integral representation of the next available char-acter
of input. It returns -1 when end of file is encountered
int read (char buffer []) attempts to read buffer. length characters into the buffer and
returns the total number of characters successfully read. It re-turns
-I when end of file is encountered
int read (char buffer [], attempts to read ‘nChars’ characters into the buffer startingat
int loc, int nChars) buffer [loc] and returns the total number of characters suc-
cessfully read. It returns -1 when end of file is encountered
long skip (long nChars) skips ‘nChars’ characters of the input stream and returns the
number of actually skipped characters
void close () closes the input source. If an attempt is made to read even
after closing the stream then it generates IOException
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
Method Description
void write () writes data to the output stream
void write (int i) Writes a single character to the output stream
void write (char buffer [] ) writes an array of characters to the output stream
void write(char buffer [],int writes ‘n’ characters from the buffer starting atbuffer [loc]
loc, int nChars) to the output stream
void close () closes the output stream. If an attempt is made to perform
writing operation even after closing the streamthen it generates
IOException
void flush () flushes the output stream and writes the waitingbuffered
output characters
Predefined Streams
Java provides the following three standard streams −
Standard Input − refers to the standard InputStream which is the keyboard by
default. This is used to feed the data to user’s program and represented as
System.in.
Standard Output − refers to the standard OutputStream by default,this is console
and
represented as System.out.
Standard Error − This is used to output the error data produced by the user’s
programand usually a computer screen is used for standard error stream and
representedas System.err.
The System class is defined in java.lang package. It contains three predefined stream vari-
ables: in, out, err. These are declared as public and static within the system.
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
java.io.*;
class Main
{
public static void main( String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char c;
do
{
c = (char)br.read(); //Reading
characterSystem.out.println(c);
}
while(c!=’@’);
}
}
Sample Output:
Enter characters, @ to
quitabcd23@
a
b
c
d
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
2
3
@
Example:
Read string from keyboard
The readLine() function with BufferedReader class’s object is used to read string from
keyboard.
Syntax:
String readLine() throws IOException
Example :
import java.io.*;
public class Main{
public static void main(String args[])throws Exception
{
Console output is most easily accomplished with print( ) and println( ). These
methodsare defined by the class PrintStream (which is the type of object referenced
by System. out).
Since PrintStream is an output stream derived from OutputStream, it also
implements the low-level method write( ).
So, write( ) can be used to write to the console.
Syntax:
void write(int byteval)
This method writes to the stream the byte specified by byteval.
The following java program uses write( ) to output the character “A” followed by a new-
line to the screen:
// Demonstrate
System.out.write().class
WriteDemo
{
public static void main(String args[])
{
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
recommendedmostly for debugging purposes or for sample programs.
For real-world 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 it easier to internationalize
our program.
PrintWriter defines several constructors.
Syntax:
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
pw.println(“This is a string”);
int i = -7;
pw.println(i);
double d = 4.5e7;
pw.println(d);
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
}
}
Sample Output:
This is a string
-7
4.5E-7
READING AND WRITING FILES
In Java, all files are byte-oriented, and Java provides methods to read and write bytes from
and to a file.
Two of the most often-used stream classes are FileInputStream and FileOutputStream,
which create byte streams linked to files.
File Input Stream
This stream is used for reading data from the files. Objects can be created using the key-
word new and there are several types of constructors available.
The two constructors which can be used to create a FileInputStream object:
i) Following constructor takes a file name as a string to create an input stream object
toread the file:
InputStream f = new FileInputStream(“filename “);
ii) Following constructor takes a file object to create an input stream object to read
thefile. First we create a file object using File() method as follows:
File f = new File(“C:/java/hello”);
InputStream f = new FileInputStream(f);
Methods to read to stream or to do other operations on the stream.
Method Description
public void close() throws Closes the file output stream.
IOException{} Releases any system resources associated with the
file.
Throws an IOException.
public int read(int r)throws Reads the specified byte of data from the InputStream.
IOException{} Returns an int.
Returns the next byte of data and -1 will be returned if it’s
the end of the file.
public int read(byte[] r) Reads r.length bytes from the input stream into an
throws IOException{} array.
Returns the total number of bytes read. If it is the end of the
file, -1 will be returned.
public int available() throws Gives the number of bytes that can be read from this file
IOException{} input stream.
Returns an int.
ii) Following constructor takes a file object to create an output stream object to write
thefile. First, we create a file object using File() method as follows:
File f = new File(“C:/java/hello”);
OutputStream f = new FileOutputStream(f);
Methods to write to stream or to do other operations on the stream
Method Descriptio
n
public void close() throws Closes the file output stream.
IO-Exception{} Releases any system resources associated with
the
file.
Throws an IOException.
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department: Computer Science and Engineering (AIML)
System.out.print(“Exception”);
}
}
}
The above code creates a file named test.txt and writes given numbers in binary format.
The same will be displayed as output on the stdout screen.