View
62
Download
2
Category
Preview:
Citation preview
MODULE 6 exception handling andFiles and streams
LESSON 6 EXCEPTION HANDLING
Leaning Objectives:
Keywords and Phrases
LEARNER
INTRODUCTION
Advanced Programming Page 1
Try File InputStreamCatch Streams OutputStreamThrow
When you finish this lesson, you will be able to do the following:
Define exceptions
Describe the use of the keywords try, catch, and finally.
Identify Common Exceptions
Write code to handle your own exceptions.
Read and write text to files and streams.
Read and write text to files and streams.
An exception is an error thrown by a class or method reporting an error in
operation. For example, dividing by zero is undefined in mathematics, and a
calculation can fail if this winds up being the case because of an error in user input. In
this particular case an ArithmeticException is thrown, and unless the programmer
looks for this exception and manually puts in code to handle it, the program will crash
stating the exception thrown and a stack trace, which would be unhelpful to a user of
a Java program. If the programmer handles the exception, he could deliver a useful
error to the user and return the user to the beginning of the program so that they
could continue to use it.
EXCEPTION HANDLING IN JAVA
What Is an Exception?
An exception is an event, which occurs during the execution of a program, that
disrupts the normal flow of the program's instructions.
When an error occurs within a method, the method creates an object and hands it off
to the runtime system. The object, called an exception object, contains information
about the error, including its type and the state of the program when the error
occurred. Creating an exception object and handing it to the runtime system is called
throwing an exception.
After a method throws an exception, the runtime system attempts to find something to
handle it. The set of possible "methods" to handle the exception is the ordered list of
methods that had been called to get to the method where the error occurred. The list
of methods is known as the call stack.
The runtime system searches the call stack for a method that contains a block of
code that can handle the exception. This block of code is called an exception
Advanced Programming Page 2
handler. The search begins with the method in which the error occurred and
proceeds through the call stack in the reverse order in which the methods were
called. When an appropriate handler is found, the runtime system passes the
exception to the handler. An exception handler is considered appropriate if the type of
the exception object thrown matches the type that can be handled by the handler.
The exception handler chosen is said to catch the exception. If the runtime system
exhaustively searches all the methods on the call stack without finding an appropriate
exception handler, as shown in the next figure, the runtime system (and,
consequently, the program) terminates.
The Catch or Specify Requirement
Valid Java programming language code must honor the Catch or Specify
Requirement. This means that code that might throw certain exceptions must be
enclosed by either of the following:
A try statement that catches the exception. The try must provide a
handler for the exception.
A method that specifies that it can throw the exception. The method
must provide a throws clause that lists the exception.
Code that fails to honor the Catch or Specify Requirement will not compile.
Not all exceptions are subject to the Catch or Specify Requirement. To understand
why, we need to look at the three basic categories of exceptions, only one of which is
subject to the Requirement.
The Three Kinds of Exceptions
Advanced Programming Page 3
The first kind of exception is the checked exception. These are exceptional
conditions that a well-written application should anticipate and recover from. For
example, suppose an application prompts a user for an input file name, then opens
the file by passing the name to the constructor for java.io.FileReader. Normally, the
user provides the name of an existing, readable file, so the construction of the
FileReader object succeeds, and the execution of the application proceeds normally.
But sometimes the user supplies the name of a nonexistent file, and the constructor
throws java.io.FileNotFoundException. A well-written program will catch this
exception and notify the user of the mistake, possibly prompting for a corrected file
name.
Checked exceptions are subject to the Catch or Specify Requirement. All exceptions
are checked exceptions, except for those indicated by Error, RuntimeException, and
their subclasses.
The second kind of exception is the error. These are exceptional conditions that are
external to the application, and that the application usually cannot anticipate or
recover from. For example, suppose that an application successfully opens a file for
input, but is unable to read the file because of a hardware or system malfunction. The
unsuccessful read will throw java.io.IOError. An application might choose to catch this
exception, in order to notify the user of the problem — but it also might make sense
for the program to print a stack trace and exit.
Errors are not subject to the Catch or Specify Requirement. Errors are those
exceptions indicated by Error and its subclasses.
The third kind of exception is the runtime exception. These are exceptional
conditions that are internal to the application, and that the application usually cannot
anticipate or recover from. These usually indicate programming bugs, such as logic
errors or improper use of an API. For example, consider the application described
previously that passes a file name to the constructor for FileReader. If a logic error
causes a null to be passed to the constructor, the constructor will throw
Advanced Programming Page 4
NullPointerException. The application can catch this exception, but it probably makes
more sense to eliminate the bug that caused the exception to occur.
Runtime exceptions are not subject to the Catch or Specify Requirement. Runtime
exceptions are those indicated by RuntimeException and its subclasses.
Errors and runtime exceptions are collectively known as unchecked exceptions.
Common Exceptions
There are many different exceptions that can be thrown by a program, and the Java
API contains quite a few. A lot are contained in the default package, java.lang;
however, when you start using more functionality such as AWT, Swing, or java.io, the
packages may also contain additional exceptions thrown by those libraries. As you
start expanding the functionality, it might be a good idea to look at potential
exceptions in the package and when they might be thrown in the course of your
application. Here is a primer of some:
ArithmeticException--thrown if a program attempts to perform division by zero
ArrayIndexOutOfBoundsException--thrown if a program attempts to access an
index of an array that does not exist
StringIndexOutOfBoundsException--thrown if a program attempts to access a
character at a non-existent index in a String
NullPointerException--thrown if the JVM attempts to perform an operation on
an Object that points to no data, or null
NumberFormatException--thrown if a program is attempting to convert a string
to a numerical datatype, and the string contains inappropriate characters (i.e.
'z' or 'Q')
ClassNotFoundException--thrown if a program can not find a class it depends
at runtime (i.e., the class's ".class" file cannot be found or was removed from
the CLASSPATH)
IOException--actually contained in java.io, but it is thrown if the JVM failed to
open an I/O stream
Advanced Programming Page 5
"Catching" Exceptions
The java language contains keywords used specifically for testing for and handling
exceptions. The ones we will be using here are try and catch, and they must be used
in conjunction with one another. They sort of work like if-else:
try{
/*
Contains code to be tested
*/
}catch(Exception e){
/*
Contains code to be executed if instanced of Exception is caught
*/
}
The catch statement can look for all exceptions, using the Exception superclass, or it
can catch a specific exception that you think could be thrown in the code you are
testing with the try block. You can even have multiple catch blocks to catch and
execute custom code for a number of different errors. A good thing to note would be
that any particular exception that is caught is compared with each catch statement
sequentially; so it is a good idea to put more generic exceptions, like Exception,
towards the bottom of the list.
The Throwable Superclass
Advanced Programming Page 6
The catch statement also stores an instance of the exception that was caught in the
variable that the programmer uses, in the previous example Exception e. While all
exceptions are subclasses of Exception, Exception itself is a subclass of Throwable,
which contains a nice suite of methods that you can use to get all kinds of information
to report about your exceptions:
getMessage()--returns the error message reported by the exception in a String
printStackTrace()--prints the stack trace of the exception to standard output,
useful for debugging purposes in locating where the exception occurred
printStackTrace(PrintStream s)--prints the stack trace to an alternative output
stream
printStackTrace(PrintWriter s)--prints the stack trace to a file, this way you can
log stack traces transparent to the user or log for later reference
toString()--if you just decide to print out the exception it will print out this:
NAME_OF_EXCEPTION: getMessage().
Example:
class ExcHandlingExample {
public static void main(String args[]) {
int x, y;
try { // monitor a block of code.
x = 0;
y = 50 / x;
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.");
Advanced Programming Page 7
}
}
Output:
Notice that the call to println( ) inside the try block is never executed. Once an
exception is thrown, program control transfers out of the try block into the catch block. Put differently, catch is not "called," so execution never "returns" to the try block from a catch. Thus, the line "This will not be printed." is not displayed. Once
the catch statement has executed, program control continues with the next line in the
program following the entire try/catch mechanism.
A try and its catch statement form a unit. The scope of the catch clause is restricted
to those statements specified by the immediately preceding try statement. A catch statement cannot catch an exception thrown by another try statement (except in the
case of nested try statements, described shortly). The statements that are protected
by try must be surrounded by curly braces. (That is, they must be within a block.)
You cannot use try on a single statement.
The goal of most well-constructed catch clauses should be to resolve the exceptional
condition and then continue on as if the error had never happened. For example, in
the next program each iteration of the for loop obtains two random integers. Those
Advanced Programming Page 8
two integers are divided by each other, and the result is used to divide the value
12345. The final result is put into a. If either division operation causes a divide-by-
zero error, it is caught, the value of a is set to zero, and the program continues.
// Handle an exception and move on.
import java.util.Random;
class HandleErrorExample {
public static void main(String args[]) {
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<32000; i++) {
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
}
catch (ArithmeticException e) {
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}
}
Multiple try catch
Advanced Programming Page 9
The code which can throw exception should be written in the try block. If the
exceptions occurs at that particular block then it will be catch by the catch block. We
can have more than one try/catch block. The most specific exception which can be
thrown is written on the top in the catch block following by the less specific least.
The code of the program is given program:
// Multiple catch
class MultipleCatchExample {
public static void main(String args[]) {
try {
int a[] =new int[6];
for(int i = 0; i<7; i++){
a[i]=i;
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds.");
} catch(ArithmeticException e) {
System.out.println("Arithmetic exception: " + e);
} catch(Exception e) {
System.out.println("An error occurred: " + e);
}
}
}
Output:
Advanced Programming Page 10
Nested try catch
The code which can throw exception should be written in the try block. If the
exceptions occurs at that particular block then it will be catch by the catch block. We
can have more than one try/catch block. We can declare multiple try blocks inside the
try block. The most specific exception which can be thrown is written on the top in the
catch block following by the less specific least.
The code of the program is given program:
// Nested Try Catch
class NestedTryCatchExample {
public static void main(String args[]) {
try {
int c[] = {0, 1, 2, 3};
try {
c[5] = 5;
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("<br>Array index out of bounds: " + e);
}
int a=c[3]/c[0];
} catch(ArithmeticException e) {
Advanced Programming Page 11
System.out.println("<br>Divide by zero: " + e);
}
}
}
Output:
How to Throw Exceptions in Java
Before catching an exception it is must to be thrown first. This means that there
should be a code somewhere in the program that could catch the exception. We use
throw statement to throw an exception or simply use the throw keyword with an object
reference to throw an exception. A single argument is required by the throw statement i.e. a throwable object. As mentioned earlier Throwable objects are
instances of any subclass of the Throwable class.
throw new VeryFastException();
Note: The reference should be of type Throwable or one of its subclasses.
For instance the example below shows how to throw an exception. Here we are trying
to divide a number by zero so we have thrown an exception here as "throw new
MyException("can't be divided by zero");"
class MyException extends Exception {
Advanced Programming Page 12
public MyException(String msg){
super(msg);
}
}
public class Test {
static int divide(int first,int second) throws MyException{
if(second==0)
throw new MyException("can't be divided by zero");
return first/second;
}
public static void main(String[] args) {
try {
System.out.println(divide(4,0));
}
catch (MyException exc) {
exc.printStackTrace();
}
}
}
WORKING WITH FILES AND STREAMS
The Java Input/Output (I/O) is a part of java.io package. The java.io package
contains a relatively large number of classes that support input and output
operations. The classes in the package are primarily abstract classes and stream-
oriented that define methods and subclasses which allow bytes to be read from and
written to files or other input and output sources.
Advanced Programming Page 13
The InputStream and OutputStream are central classes in the package which are
used for reading from and writing to byte streams, respectively.
The java.io package can be categories along with its stream classes in a hierarchy
structure shown below:
InputStream:
The InputStream class is used for reading the data such as a byte and array of bytes
from an input source. An input source can be a file, a string, or memory that may
contain the data. It is an abstract class that defines the programming interface for all
input streams that are inherited from it. An input stream is automatically opened when
you create it. You cans explicitly close a stream with the close( ) method, or let it be
closed implicitly when the object is found as a garbage.
Advanced Programming Page 14
The subclasses inherited from the InputStream class can be seen in a hierarchy
manner shown below:
InputStream is inherited from the Object class. Each class of the InputStreams
provided by the java.io package is intended for a different purpose.
OutputStream:
The OutputStream class is a sibling to InputStream that is used for writing byte and
array of bytes to an output source. Similar to input sources, an output source can be
anything such as a file, a string, or memory containing the data. Like an input stream,
an output stream is automatically opened when you create it. You can explicitly close
an output stream with the close( ) method, or let it be closed implicitly when the
object is garbage collected.
The classes inherited from the OutputStream class can be seen in a hierarchy
structure shown below:
Advanced Programming Page 15
OutputStream is also inherited from the Object class. Each class of the
OutputStreams provided by the java.io package is intended for a different purpose.
How Files and Streams Work?
Java uses streams to handle I/O operations through which the data is flowed from
one location to another. For example, an InputStream can flow the data from a disk
file to the internal memory and an OutputStream can flow the data from the internal
memory to a disk file. The disk-file may be a text file or a binary file. When we work
with a text file, we use a character stream where one character is treated as per
byte on disk. When we work with a binary file, we use a binary stream.
Classes and Interfaces of the I/O Streams
Classes:
The following listing of classes are provided by the java.io package shown in the table:
Class Description
BufferedInputStream It used for creating an
internal buffer array. It
supports the mark and reset
methods.
BufferedOutputStream This class used for writes
byte to output stream. It
Advanced Programming Page 16
implements a buffered output
stream.
BufferedReader This class provides read text
from character input stream
and buffering characters. It
also reads characters, arrays
and lines.
BufferedWriter This class provides write text
from character output stream
and buffering characters. It
also writes characters,
arrays and lines.
ByteArrayInputStream It contains the internal buffer
and read data from the
stream.
ByteArrayOutputStream This class used for data is
written into byte array. This
is implement in output
stream class.
CharArrayReader It used for char input stream
and implements a character
buffer.
CharArrayWriter This class also implements a
character buffer and it uses
an writer.
DataInputStream This class reads the primitive
data types from the input
stream in a machine format.
DataOutputStream This class writes the
primitive data types from the
Advanced Programming Page 17
output stream in machine
format.
File This class shows a file and
directory pathnames.
FileDescriptor This class uses for create a
FileInputStream and
FileOutputStream.
FileInputStream It contains the input byte
from a file and implements
an input stream.
FileOutputStream It uses for writing data to a
file and also implements an
output stream.
FilePermission It provides the permission to
access a file or directory.
FileReader This class used for reading
characters file.
FileWriter This class used for writing
characters files.
FilterInputStream This class overrides all
methods of InputStream and
contains some other input
stream.
FilterOutputStream This class overrides all
methods of OutputStream
and contains some other
output stream.
FilterReader It reads the data from the
filtered character stream.
Advanced Programming Page 18
FilterWriter It writes data from the filtered
character stream.
InputStream This class represents an
input stream of bytes.
InputStreamReader It reads bytes and decodes
them into characters.
LineNumberReader This class has a line
numbers
ObjectInputStream This class used for recover
the object to serialize
previously.
ObjectInputStream.GetField This class access to
president fields read form
input stream.
ObjectOutputStream This class used for write the
primitive data types and also
write the object to read by
the ObjectInputStream.
ObjectOutputStream.GetFieldThis class access to
president fields write in to
ObjectOutput.
ObjectStreamClass Serialization's descriptor for
classes.
ObjectStreamField This class describes the
serializable field.
OutputStream This class represents an
output stream of bytes.
OutputStreamWriter It writes bytes and decodes
them into characters.
Advanced Programming Page 19
PipedInputStream In this class the data bytes
are written into piped output
stream. This class also
connected into a piped
output stream.
PipedOutputStream This class also
communicates the piped
input stream into piped
output stream. It creates
communication between
both.
PipedReader It is a piped character-input
stream.
PipedWriter It is a piped character-output
stream.
PrintStream This class adds the
functionality of another
output stream.
PrintWriter This class adds the
functionality of another input
stream.
PushbackInputStream It also include the another
function of input stream.
Such as: "push back" or
"unread" one byte.
PushbackReader This is a character stream
reader and reads the data
push back into the stream.
RandomAccessFile It supports both reading and
writing to a random access
Advanced Programming Page 20
file.
Reader It used for reading character
stream.
SequenceInputStream It represents the logical
concatenation of other input
stream.
SerializablePermission This is a serializable
permission class.
StreamTokenizer It takes an input stream and
parse it into "tokens" . The
token to be allowed at the
read time.
StringReader This is a character string
class. It has character read
source.
StringWriter This is also a character
string class. It uses to shows
the output in the buffer.
Writer It uses for writing to
character stream.
Interfaces:
The following summary of Interfaces provided by the java.io package shown in the table:
Interface Description
DataInput This interface can be used for
reading byte stream and
reconstructing the java primitive
Advanced Programming Page 21
data types.
DataOutput This interface can be used for
writing the byte stream and
converting data from the java
primitive data types.
Externalizable This is written in Serializable
Stream. It save and store it's
contents.
FileFilter It can be used for Filtering the
Pathnames.
FilenameFilter This interface used for Filter the
Filenames.
ObjectInput This interface used for reading of
objects and it extends the
DataInput interface.
ObjectInputValidation This is a Callback interface. It
allows the validation of objects
within a graph.
ObjectOutput This interface used for writing of
objects and it extends the
DataOutput interface.
ObjectStreamConstants
This interface used for Constants
writing into Serialization Objects
Stream.
Serializable This interface implementing in the
java.io.Serializable interface.
Exceptions Classes:
Advanced Programming Page 22
The following summary of the exception classes provided by the java.io package shown
in the table:
Exceptions Description
CharConversionException It provides detail message
in the catch block to
associated with the
CharConversionException
EOFException This exception indicates
the end of file. When the
file input stream to be end
then EOFException to be
occuted.
FileNotFoundException When the open file's
pathname does not find
then this exception to be
occured.
InterruptedIOException When the I/O operations to
interrupted from any
causes then it becomes.
InvalidClassException Any problems to be
created with class, when
the Serializing runtime to
be detected.
InvalidObjectException When the de-serialized
objects failed then it
occurs.
IOException When the I/O operations to
be failed then it occurs.
NotActiveException The Serialization or
Advanced Programming Page 23
deserialization operations
are not active then it
occurs.
NotSerializableException This exception when the
instance is required to a
Serializable interface.
ObjectStreamException This is a supper class of all
exception class. It used for
specific to Object Stream
Classes.
OptionalDataException When the reading data
operations to failed then it
these exception occurs. It
is belonging to the
serialized object
StreamCorruptedException It thrown when the control
information that was read
form an object stream
vioaltes internal
consistency checks.
SyncFaieldException The sync operation is
failed then
SyncFaieldException to be
occure.
UnsupportedEncodingExceptionThe Character Encoding is
not supported.
UTFDataFormatException A molformed UTF-8 has
been read in a data input
stream, it implemented by
data input interface.
Advanced Programming Page 24
WriteAbortedException In this exception to be
thrown by the
ObjectStreamException
during a write operating.
Reading Text from the Standard Input
Standard Streams:
Standard Streams are a feature provided by many operating systems. By default,
they read input from the keyboard and write output to the display. They also support
I/O operations on files.
Java also supports three Standard Streams:
Standard Input: Accessed through System.in which is used to read input from the keyboard.
Standard Output: Accessed through System.out which is used to write output to be display.
Standard Error: Accessed through System.err which is used to write error output to be display.
These objects are defined automatically and do not need to be opened explicitly.
Standard Output and Standard Error, both are to write output; having error output
separately so that the user may read error messages efficiently.
System.in is a byte stream that has no character stream features. To use Standard
Input as a character stream, wrap System.in within the InputStreamReader as an
argument.
InputStreamReader inp = new InputStreamReader(system.in);
Working with Reader classes:
Advanced Programming Page 25
Java provides the standard I/O facilities for reading text from either the file or the
keyboard on the command line. The Reader class is used for this purpose that is
available in the java.io package. It acts as an abstract class for reading character
streams. The only methods that a subclass must implement are read(char[], int, int) and close(). the Reader class is further categorized into the subclasses. The
following diagram shows a class-hierarchy of the java.io.Reader class.
However, most subclasses override some of the methods in order to provide higher
efficiency, additional functionality, or both.
InputStreamReader:
An InputStreamReader is a bridge from byte streams to character streams i.e. it
reads bytes and decodes them into Unicode characters according to a particular
platform. Thus, this class reads characters from a byte input stream. When you
create an InputStreamReader, you specify an InputStream from which, the
InputStreamReader reads the bytes.
The syntax of InputStreamReader is written as:
InputStreamReader <variable_name> = new InputStreamReader(system.in)
BufferedReader :
Advanced Programming Page 26
The BufferedReader class is the subclass of the Reader class. It reads character-
input stream data from a memory area known as a buffer maintains state. The buffer
size may be specified, or the default size may be used that is large enough for text
reading purposes. BufferedReader converts an unbuffered stream into a buffered stream using the
wrapping expression, where the unbuffered stream object is passed to the
constructor for a buffered stream class.
For example the constructors of the BufferedReader class shown as:
BufferedReader(Reader in):Creates a buffering character-input
stream that uses a default-sized input buffer.
BufferedReader(Reader in, int sz): Creates a buffering
character-input stream that uses an input buffer of the specified
size.
BufferedReader class provides some standard methods to perform specific reading
operations shown in the table. All methods throws an IOException, if an I/O error
occurs.
Method Return Type
Description
read( ) int Reads a single character
read(char[] cbuf,
int off, int len) int
Read characters into a portion
of an array.
readLine( ) String
Read a line of text. A line is
considered to be terminated by
('\n').
close( ) void Closes the opened stream.
This program illustrates you how to use standard input stream to read the user
input..
Advanced Programming Page 27
import java.io.*;
public class ReadStandardIOExample{
public static void main(String[] args) throws IOException{
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
System.out.println("Enter text : ");
String str = in.readLine();
System.out.println("You entered String : ");
System.out.println(str);
}
}
Working With File
In the previous chapter, we learned how to work with the streams. which provide a
simple model for reading and writing data. However, streams don't support all the
operations that are common with a disk file. In lesson, we will learn how to work with
a file using the non-stream file I/O.
The File class deals with the machine dependent files in a machine-independent
manner i.e. it is easier to write platform-independent code that examines and
manipulates files using the File class. This class is available in the java.lang
package.
The java.io.File is the central class that works with files and directories. The
instance of this class represents the name of a file or directory on the host file
system.
Advanced Programming Page 28
When a File object is created, the system doesn't check to the existence of a
corresponding file/directory. If the file exist, a program can examine its attributes and
perform various operations on the file, such as renaming it, deleting it, reading from
or writing to it.
The constructors of the File class are shown in the table:
Constructor Description
File(path)
Create File object for default
directory (usually where program is
located).
File(dirpath,fname) Create File object for directory
path given as string.
File(dir, fname) Create File object for directory.
Thus the statement can be written as:
File f = new File(“<filename>”);
The methods that are used with the file object to get the attribute of a corresponding file shown in
the table.
Method Description
f.exists() Returns true if file exists.
f.isFile() Returns true if this is a normal file.
f.isDirectory() true if "f" is a directory.
f.getName() Returns name of the file or
directory.
Advanced Programming Page 29
f.isHidden() Returns true if file is hidden.
f.lastModified() Returns time of last modification.
f.length() Returns number of bytes in file.
f.getPath() path name.
f.delete() Deletes the file.
f.renameTo(f2) Renames f to File f2. Returns true
if successful.
f.createNewFile() Creates a file and may throw
IOException.
Create File in Java
Whenever the data is need to be stored, a file is used to store the data. File is a
collection of stored information that are arranged in string, rows, columns and lines
etc.
In this section, we will see how to create a file. This example takes the file name and
text data for storing to the file.
For creating a new file File.createNewFile( ) method is used. This method returns a
boolean value true if the file is created otherwise return false. If the mentioned file for
the specified directory is already exist then the createNewFile() method returns the
false otherwise the method creates the mentioned file and return true.
Example:
import java.io.*;
public class CreateFileExample{
public static void main(String[] args) throws IOException{
File f;
f=new File("myfile.txt");
if(!f.exists()){
Advanced Programming Page 30
f.createNewFile();
System.out.println("New file \"myfile.txt\" has been created to the current
directory");
}
}}
Output:
Read File Line by Line
Lets understand some I/O streams that are used to perform reading and writing
operation in a file. In the section of Java Tutorial you will learn how to write java
program to read file line by line.
Java supports the following I/O file streams.
FileInputstream FileOutputStream
FileInputstream:
This class is a subclass of Inputstream class that reads bytes from a specified file
name . The read() method of this class reads a byte or array of bytes from the file. It
returns -1 when the end-of-file has been reached. We typically use this class in
Advanced Programming Page 31
conjunction with a BufferedInputStream and DataInputstream class to read binary
data. To read text data, this class is used with an InputStreamReader and
BufferedReader class. This class throws FileNotFoundException, if the specified
file is not exist. You can use the constructor of this stream as:
FileInputstream(File filename);
FileOutputStream:
This class is a subclass of OutputStream that writes data to a specified file name.
The write() method of this class writes a byte or array of bytes to the file. We typically
use this class in conjunction with a BufferedOutputStream and a DataOutputStream class to write binary data. To write text, we typically use it with a
PrintWriter, BufferedWriter and an OutputStreamWriter class. You can use the
constructor of this stream as:
FileOutputstream(File filename);
DataInputStream:
This class is a type of FilterInputStream that allows you to read binary data of Java
primitive data types in a portable way. In other words, the DataInputStream class is
used to read binary Java primitive data types in a machine-independent way. An
application uses a DataOutputStream to write data that can later be read by a
DataInputStream. You can use the constructor of this stream as:
DataInputStream(FileOutputsream finp);
The following program demonstrate, how the contains are read from a file.
import java.io.*;
Advanced Programming Page 32
public class ReadFileExample{
public static void main(String[] args) throws IOException{
File f;
f=new File("myfile.txt");
if(!f.exists()&& f.length()<0)
System.out.println("The specified file is not existing");
else{
FileInputStream finp=new FileInputStream(f);
byte b;
do{
b=(byte)finp.read();
System.out.print((char)b);
}
while(b!=-1);
finp.close();
}
}
}
Output:
Advanced Programming Page 33
Another program use DataInputStreams for reading textual input line by line with an
appropriate BufferedReader.
import java.io.*;
class FileReadExample
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("myfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Output:
Advanced Programming Page 34
Writing To File
In the section, you will learn how to write data to a file. As we have discussed, the
FileOutputStream class is used to write data to a file.
Lets see an example that writes the data to a file converting into the bytes.
This program first check the existence of the specified file. If the file exist, the data is
written to the file through the object of the FileOutputStream class.
import java.io.*;
public class WriteFileExample{
public static void main(String[] args) throws IOException{
File f=new File("textfileSample.txt");
FileOutputStream fop=new FileOutputStream(f);
if(f.exists()){
String str="This data is written through the program";
fop.write(str.getBytes());
Advanced Programming Page 35
fop.flush();
fop.close();
System.out.println("The data has been written");
}
else
System.out.println("This file is not existing");
}
}
Append To File
In the section, you will learn how the data is appended to an existing file. We will use
the class FileWriter and BufferedWriter to append the data to a file.
FileWriterThe FileWriter is a class used for writing character files. The constructors of this class
assume that the default character encoding and the default byte-buffer size are
acceptable. This constructor simply overwrite the contents in the file by the specified
string but if you put the boolean value as true with the file name (argument of the
constructor) then the constructor append the specified data to the file i.e. the pre-exist
data in a file is not overwritten and the new data is appended after the pre-exist data.
BufferedWriter
Advanced Programming Page 36
The BufferWriter class is used to write text to a character-output stream, buffering
characters so as to provide for the efficient writing of single characters, arrays, and
strings.
Here is the code of java program to write text to a file:
import java.io.*;
class FileWriteExample
{
public static void main(String args[])
{
try{
// Create file
FileWriter fstream = new FileWriter("txtfileSample.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Output:
Advanced Programming Page 37
Getting the Size of a File in Java
In this section you will learn how to get the size (in bytes) of a specified file. you will
also learn about the methods that can be used to get the file size. If you give the text
based file then the program tells you the number of characters otherwise it will give
you the file size in bytes.
Program takes the file name through the keyboard and checks whether the file exists.
If the file exists then the length( ) method of the instance of the File class gives you
size of the file.
Here is the code of the program :
import java.io.*;
public class FileSizeExample{
public static void main(String[] args) throws IOException{
System.out.print("Enter file name : ");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
File f = new File(in.readLine());
if(f.exists()){
long file_size = f.length();
System.out.println("Size of the file : " + file_size);
}
else{
Advanced Programming Page 38
System.out.println("File does not exists.");
System.exit(0);
}
}
}
Output:
Count lines of a particular file
In this section, you will learn how to count the availability of text lines in the particular
file. A file is read before counting lines of a particular file. File is a collection of
stored information that are arranged in string, rows, columns and lines etc. Try it for
getting the lines through the following program.
Description of program:
The following program helps you in counting lines of a particular file. At the execution
time of this program, it takes a file name with its extension from a particular directory
and checks it using the exists() method. If the file exists, it will count lines of a
particular file otherwise it will display a message "File does not exists!".
Description of code:
Advanced Programming Page 39
FileReader(File file):This is the constructor of FileReader class that is reliable for reading a character
files. It constructs a new FileReader and takes a file name that have to be read.
FileNumberReader():This is the constructor of FileNumberReader class. It constructs a new line-
numbering reader. It reads characters and puts into buffer. By default the numbering
of line begins from '0'.
Here is the code of program:
import java.io.*;
public class NumberOfLinesExample{
public static void main(String[] args) {
try{
System.out.println("Getting line number of a file.");
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter file name with extension:");
String str = bf.readLine();
File file = new File(str);
if (file.exists()){
FileReader fr = new FileReader(file);
LineNumberReader ln = new LineNumberReader(fr);
int count = 0;
while (ln.readLine() != null){
count++;
}
System.out.println("Total line no: " + count);
ln.close();
}
Advanced Programming Page 40
else{
System.out.println("File does not exists!");
}
}
catch(IOException e){
e.printStackTrace();
}
}
}
Output:
Reading Assignment:
E-books
o http://java.sun.com/docs/books/tutorial/
o http://www.java-samples.com/showtutorial.php?tutorialid=293
o http://roseindia.n et/jsp/simple-jsp-example/nesting-try.shtml
o http://www.roseindia.net/java/example/java
Book
o Java How to Program by Deitel and Deitel, Latest edition
o Java Programming, Joyce Farrel Latest edition
Exercises/Written Assignments
1. Be able to differentiate the following items:
Advanced Programming Page 41
a) The three kinds of Exception
b) Common Exception
c) Catching Exception
d) Throwable Superclass
e) InputStream
f) OutputStream
g) The different Standards of Streams
h) BufferedReader
2. List the advantages of exception handling.
3. Under what circumstances would you use the following statement?
Catch(…) (throw; )
Programming Problems
1. Design and write a Java class that will create a text file of your favorite
quotations or famous lines from your favorite authors. Your program will
have the facility to add new quotations and search quotations from the text
file.
2. Write a program that prompts the user to enter a number. Subtract 60 from
the number and then declare an array using the calculated size. If you
attempt to declare an array whose computed size is negative, the program
should throw an exception. Use a catch block to catch the Exception if
there is one, and then display the associated message.
3. Write a program that allows the user to create a file of employees and their
e-mail numbers. Prompt the user to enter the names and e-mail numbers.
The program then displays the data from the file just created.
References/Bibliography
http://java.sun.com/docs/books/tutorial/
Advanced Programming Page 42
http://www.java-samples.com/showtutorial.php?tutorialid=293
http://roseindia.net/jsp/simple-jsp-example/nesting-try.shtml
http://www.roseindia.net/java/example/java
Java How to Program by Deitel and Deitel, Latest edition
Java Programming, Joyce Farrel Latest edition
Advanced Programming Page 43
Recommended