0% found this document useful (0 votes)
5 views32 pages

Java Exception Handling Explained

The document provides an overview of exception handling and multithreading in Java. It explains the types of exceptions, exception handling techniques using keywords like try, catch, throw, and finally, as well as the creation and lifecycle of threads. Additionally, it covers user-defined exceptions and the differences between process-based and thread-based multitasking.

Uploaded by

santhosh t
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views32 pages

Java Exception Handling Explained

The document provides an overview of exception handling and multithreading in Java. It explains the types of exceptions, exception handling techniques using keywords like try, catch, throw, and finally, as well as the creation and lifecycle of threads. Additionally, it covers user-defined exceptions and the differences between process-based and thread-based multitasking.

Uploaded by

santhosh t
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit-II

1. Exception:
 Exception is a problem that arises at the time of program execution.
 When an exception occurs, it disrupts the program execution flow.
 When an exception occurs, the program execution gets terminated, and the system
generates an error. We use the exception handling mechanism to avoid abnormal
termination of program execution.

Reasons for Exception Occurrence


Exceptions can arise due to a number of situations. For example,
 Trying to access the 11th element of an array when the array contains only 10
elements(ArrayIndexOutOfBoundsException)
 Division by zero (ArithmeticException)
 Accessing a file which is not present (FileNotFoundException)
 Failure of I/O operations (IOException)
 Illegal usage of null (NullPointerException)

1.1 Types of Exception


In java, exceptions have categorized into two types, and they are as follows.
Checked Exception -An exception that is checked by the compiler at the time of
compilation
is called a checked exception.
Unchecked Exception -An exception that cannot be caught by the compiler but occurs at
the time of program execution is called an unchecked exception.

1
Java programming language has the following class hierarchy to support the exception
handling mechanism.

1.2 EXCEPTION HANDLING TECHNIQUES


In java, the exception handling mechanism uses five keywords namely
try, catch, finally, throw, and throws .

1.2.1 try…catch
The try and catch, both are the keywords used for exception handling.
The keywordtry is used to define a block of code that will be tests the occurence of an
exception.

2
The keywordcatchis used to define a block of code that handles the exception occurred in
the respective try block..
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Both try and catch are used as a pair. Every try block must have one or more catch blocks. We
cannot use try without at least one catch, and catch alone can be used (catch without try is
not allowed).
Syntax
try
{
...
code to be tested
...
}
catch (ExceptionType object)
{
...
code for handling the exception
...
}

Example:
class TryCatchExample
{
public static void main(String[] args)
{
try
{
int a = 10;
int b = 0;
int c = a / b;
[Link](a + "/" + b +" = " + c);
}
catch(ArithmeticException ae)
{
[Link]("Value of divisor can not be ZERO");
}
}
}

3
when an exception occurs in the try block the execution control transferred to the catch
block and the catch block handles it.

1.2.2 Multiple catch clauses


In java programming language, a try block may have one or more number of catch blocks.
That means a single try statement can have multiple catch clauses.
When a try block has more than one catch block, each catch block must contain a different
exception type to be handled.
Example:
class TryCatchExample
{
public static void main(String[] args)
{
try
{
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[10] = list[2] / list[4];
}
catch(ArithmeticException ae)
{
[Link](" Value of divisor can not be ZERO.");
}

catch(ArrayIndexOutOfBoundsExceptionaie)
{
[Link]("ArrayIndexOutOfBoundsException has
occured.");
}
catch(Exception e)
{
[Link](" Unknown exception has occured.");
}
}
}

4
1.2.3 throw Keyword
The throw keyword is used to explicitly throw an exception.
The throw keyword must be used inside the try block. When JVM encounters the throw
keyword, it stops the execution of try block and jump to the corresponding catch block.
Using throw keyword only one exception can be thrown. The throw keyword must followed
by an throwable instance.
The following is the general syntax for using throw keyword in a try block.
thrownew ThrowableInstance;

Example:

class Test
{
static void check(int age)
{
if(age<18)
throw new ArithmeticException("Not Elgible to Vote");
else
[Link]("Elgible to Vote");
}

public static void main(String args[])


{
check(20);
[Link]("Rest of the Code");
}
}

1.2.4 throws Keyword


The throws keyword specifies the exceptions that a method can throw to the default handler and
does not handle itself. That means when we need a method to throw an exception automatically, we
use throws keyword followed by method declaration.
5
throws keyword allows throw an exception from a method. If there is chance of raise any checked
exception, compulsory we have to handle otherwise compile time error we will get.
In two ways we can handle this type of exceptions

1. Using try -catch


2. Using throws keyword

throws keyword Syntax:

returntypefunctionname(args) throws Exceptiontype


{
……
……
}
Example:

import [Link].*;
class throwsException
{
public static void main(String args[]) throws FileNotFoundException
{
FileReaderfr=new FileReader(" [Link]");
}
}

throwskeyword will not handle the error, it’s convinced the compiler and avoids the
abnormal termination of a program.

1.2.5finally keyword
The finally keyword used to define a block that must be executed irrespective of exception
occurrence.
The basic purpose of finally keyword is to cleanup resources allocated by try block, such as
closing file, closing database connection, etc.

6
Syntax 1:
try
{
...
}
finally
{
....
}

Syntax 2:
try {
...
}
catch(Throwable e)
{
...
}
finally
{
....
}

Example:
class finallyExample
{
public static void main(String args[])
{
try
{
[Link](10/0);
}
catch(ArithmeticException ae)
{
[Link]("Divisble by zero");
}
finally
{
[Link]("Finally Block");
}
try
{
[Link]("try Block");
}
7
finally
{
[Link]("Java Finally Block");
}
}
}

1.2.6Rethrowing Exception
class rethrow
{
public static void main(String args[])
{
try
{
[Link](10/0);
}
catch(ArithmeticException ae)
{
throw new NumberFormatException();
}
}
}

1.3 User-Defined Exception


The Java programming language allow us to create our own exception classes which are basically
subclasses built-in class Exception.

To create our own exception class simply create a class as a subclass of built-in Exception class.

We may create constructor in the user-defined exception class and pass a string to Exception class
constructor using super(). We can use getMessage() method to access the string.

8
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}

class TestMyException
{
public static void main(String args[])
{
int x=5, y=1000;
try
{
float z= (float) x/ (float) y;
if(z<0.01)
{
throw new MyException(" Number is too
small");
}
}
catch(MyException e)
{
[Link]("Caught my exception");
[Link]([Link]());
}
}
}

9
Multithreading in java
2.1 Introduction
The java programming language allows us to create a program that contains one or more
parts that can run simultaneously at the same time. This type of program is known as a
multithreading program.
Each part of this program is called a thread. Every thread defines a separate path of execution
in java.
A thread is explained in different ways, and a few of them are as specified below.

A thread is a light weight process.

A thread may also be defined as follows.

A thread is a subpart of a process that can run individually.


In java, multiple threads can run at a time, which enables the java to write multitasking
programs.
The multithreading is a specialized form of multitasking. All modern operating systems
support multitasking.
There are two types of multitasking, and they are as follows.

 Process-based multitasking
 Thread-based multitasking

Difference between process-based and thread-based multitasking

Process-based multitasking Thread-based multitasking

It allows the computer to run two or It allows the computer to run two or more
more programs concurrently threads concurrently
In this process is the smallest unit. In this thread is the smallest unit.
Process is a larger unit. Thread is a part of process.
Process is heavy weight. Thread is light weight.
Process requires separate address
Threads share same address space.
space for each.
Process never gain access over idle
Thread gain access over idle time of CPU.
time of CPU.
Inter process communication is Inter thread communication is not
expensive. expensive.

10
2.2Creating threads in Java
In java, a thread is a lightweight process. Every java program executes by a thread called the
main thread.
When a java program gets executed, the main thread created automatically. All other threads
called from the main thread.

The java programming language provides two methods to create threads, and they are listed
below.

 Using Thread class (by extending Thread class)


 Using Runnable interface (by implementing Runnable interface)

2.2.1 Extending Thread class


The java contains a built-in class Thread inside the [Link] package. The Thread class contains
all the methods that are related to the threads.
To create a thread using Thread class, follow the step given below.
Step-1 (Declaring a Thread) : - Create a class as a child of Thread class. That means, create a class that
extends Thread class.
Syntax:
class NewThread extends Thread
{
......
......
......
}
Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
Syntax:
public void run( )
{
......
//code segment providing the functionality of thread
.....
}
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Call the start( ) method on the object created in the above step.
Syntax:
newThread thread1 = new newThread();
[Link]();

11
Example 1:
class Single extends Thread
{
public void run()
{
[Link]("Sample Thread Program");
}
}
class SampleThread
{
public static void main(String args[])
{
Single s=new Single();
[Link]();
}
}

Example 2:
class SampleThread extends Thread
{
public void run()
{
[Link]("Thread is under Running...");
for(int i= 1; i<=10; i++)
{
[Link]("i = " + i);
}
}
}
class MyThread
{
public static void main(String[] args)
{
SampleThread t1 = new SampleThread();
[Link]("Thread about to start...");
[Link]();
}
}

12
2.2.2 Implementing Runnable interface
The java contains a built-in interface Runnable inside the [Link] package.
The Runnable interface implemented by the Thread class that contains all the methods that
are related to the threads.
To create a thread using Runnable interface, follow the step given below.
Step-1: Create a class that implements Runnable interface.
Syntax:
class NewThreadimplements Runnable
{
......
......
......
}

Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
Syntax:
public void run( )
{
......
//code segment providing the functionality of thread
.....
}

Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Create the Thread class object by passing above created object as parameter to the
Thread class constructor.
Step-5: Call the start( ) method on the Thread class object created in the above step.

Example:

class SampleThread implements Runnable


{
public void run()
{
[Link]("Thread is under Running...");

for(int i= 1; i<=10; i++)

13
{
[Link]("i = " + i);
}
} }

class ThreadTest
{
public static void main(String[] args)
{
SampleThread th = new SampleThread();
Thread obj = new Thread(th);
[Link]("Thread about to start...");
[Link]();
}
}

2.3 Thread Lifecycle / Thread States

In java, a thread goes through different states throughout its execution. These stages are called
thread life cycle states or phases.

14
2.3.1 New:
In this state, a new thread is created but not started. This state is also known as Born state.

Syntax:
Thread obj = new Thread();

The above statement is responsible for creating a new Thread object At this state , we can do only
one of the following things with it:
 Schedule it for running using start() method
 Kill it using stop() method

2.3.2 Runnable / Ready:


The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor.

When a thread calls start( ) method, then the thread is said to be in the Runnable state. This
state is also known as a Ready state.

[Link]();

4.3.2 Running:
Running means that the processor has given its time to the thread for its execution.

When a thread calls run( ) method, then the thread is said to be Running. The run( )
method of a thread called automatically by the start( ) method.

4.3.3 Not Runnable:


A thread in the Running state may move into the blocked state due to various reasons like
sleep( ) method called, wait( ) method called, suspend( ) method called, and join( ) method
called, etc.

A thread which is in any of these three states can be assumed to be in ‘not runnable’ state.
These three states are WAITING, TIMED_WAITING, and BLOCKED.

Waiting :In this state, a thread is waiting indefinitely for another thread to perform a
particular
action (i.e., notify). Threads can move into this state either by calling the methods
[Link]()(without time out) or [Link]() (without time out).
15
Timed_Waiting: In this state, the thread is waiting for another thread to perform an action
(notify)up to a specified waiting time. A thread can get into this state by calling
either ofthese methods:[Link](), [Link](), and
[Link]()
(all these methods should be called withtime out specified).

Blocked :In this state, a resource cannot be accessed because it is being used by another
thread.A thread can get into this state by calling [Link]() method.

4.3.4 Terminated
A thread in the Running state may move into the dead state due to either its execution
completed or the stop( ) method called. The dead state is also known as the terminated state.

The Thread class contains the following methods.

Return
Method Description
Value

run( ) Defines actual task of the thread. void

It moves thre thread from Ready state to Running


start( ) void
state by calling run( ) method.

setName(String) Assigns a name to the thread. void

getName( ) Returns the name of the thread. String

setPriority(int) Assigns priority to the thread. void

getPriority( ) Returns the priority of the thread. int

getId( ) Returns the ID of the thread. long

activeCount() Returns total number of thread under active. int

Returns the reference of the thread that currently in


currentThread( ) void
running state.

moves the thread to blocked state till the specified


sleep( long ) void
number of milliseconds.

isAlive( ) Tests if the thread is alive. Boolean

16
Tells to the scheduler that the current thread is willing
yield( ) void
to yield its current use of a processor.

join( ) Waits for the thread to end. void

Example :

class Sample extends Thread


{
public void run()
{
for(int i=0;i<=5;i++)
{
try
{
[Link](1000);
}
catch(InterruptedExceptionie)
{

}
[Link](i);
}
}
}
class ThreadMethods
{
public static void main(String args[])
{
Sample s1=new Sample();
Sample s2=new Sample();
[Link]("Id = "+[Link]());
[Link]("Name of the Thread s1 = "+[Link]());
[Link]("Thread One");
[Link]("Name of the Thread after Changing =
"+[Link]());
[Link]("Priority of Thread s1 = "+[Link]());
[Link]("Priority of Thread s2 = "+[Link]());
[Link](6);
[Link]("After Changing Priority of Thread s1 =
"+[Link]());
[Link]();
}

17
}

Example Program on Join Method :


class Sample extends Thread
{
public void run()
{
for(int i=0;i<=5;i++)
{
try
{
[Link](1000);
}
catch(InterruptedExceptionie)
{

}
[Link](i);
}
}
}
class ThreadMethods
{
public static void main(String args[])
{
Sample s1=new Sample();
Sample s2=new Sample();
[Link]();
try
{
[Link]("Thread1
Running");
[Link]();
[Link]("Thread1 Ends");
}
catch(InterruptedException e)
{
18
}
[Link]("Thread2 Running");
[Link]();
}
}

2.4 Thread Priority


In a java programming language, every thread has a property called priority.
Most of the scheduling algorithms use the thread priority to schedule the execution
sequence.
In java, the thread priority range from 1 to 10. Priority 1 is considered as the lowest priority,
and priority 10 is considered as the highest priority.
The thread with more priority allocates the processor first.
The java programming language Thread class provides two methods setPriority(int),
and getPriority( ) to handle thread priorities.
The Thread class also contains three constants that are used to set the thread priority, and
they are listed below.

 MAX_PRIORITY - It has the value 10 and indicates highest priority.


 NORM_PRIORITY - It has the value 5 and indicates normal priority.
 MIN_PRIORITY - It has the value 1 and indicates lowest priority.

🔔The default priority of any thread is 5 (i.e. NORM_PRIORITY).

19
3. Input/Output
3.1 Introduction

The two most important parts of a computer are input and output. Input/output classes form
the core of any programming language.
The [Link] package provides separate classes for reading and writing data (byte and
character data). The java I/O facility is based on streams.
The Stream is defined in the [Link] package.

Stream is a continuous flow of data. Java provides two types of streams, and they are as
follows.

 Byte Stream
 Character Stream

Byte stream classes deal with reading and writing of bytes to files, socket, etc.
Character stream classes deal with reading and writing characters to files, socket,etc.
The [Link] contains two top level byte stream abstract
classes:[Link] (for reading bytes)and [Link](for
writing bytes).

The [Link] also contains two other level character stream abstract classes:
[Link] (for reading characters)and [Link](for writing characters).

20
The

3.2 [Link] CLASS


The File is a built-in class in Java. In java, the File class has been defined in
the [Link] package.
The File class represents a reference to a file or directory.
The File class has various methods to perform operations like creating a file or directory,
reading from a file, updating file content, and deleting a file or directory.

The File class in java has the following constructors.


Method Description
String getName() It returns the name of the file or directory that
referenced by the current File object.
String getParent() It returns the pathname of the pathname's parent, or null
if the pathname does not name a parent directory.
String getPath() It returns the path of current File.
File getParentFile() It returns the path of the current file's parent; or null
if it does not exist.
String It returns the current file or directory path from the
getAbsolutePath() root.
booleanisAbsolute() It returns true if the current file is absolute, false
otherwise.
booleanisDirectory() It returns true, if the current file is a directory;
otherwise returns false.
booleanisFile() It returns true, if the current file is a file; otherwise
returns false.
booleanexists() It returns true if the current file or directory exist;
otherwise returns false.
booleancanRead() It returns true if and only if the file specified exists
and can be read by the application; false otherwise.
booleancanWrite() It returns true if and only if the file specified exists
and the application is allowed to write to the file;
21
false otherwise.
long length() It returns the length of the current file.
long lastModified() It returns the time that specifies the file was last
modified.

booleancreateNewFile() It returns true if the named file does not exist and was
successfully created; false if the named file already
exists.

booleandelete() It deletes the file or directory. And returns true if and


only if the file or directory is successfully deleted;
false otherwise.

Example Program:

import [Link].*;
class FileDemo
{
public static void main(String args[])
{
File f = new File("D:\\[Link]");
[Link]("Existance : " + [Link]());
[Link]("Read mode : " + [Link]());
[Link]("Write mode : " + [Link]());
[Link]("Executable File : " + [Link]());
[Link]("Name of the file : " + [Link]());
[Link]("Parent name : " + [Link]());
[Link]("path of the File : " + [Link]());
[Link]("Hidden File : " + [Link]());
[Link]("Length of the File : " + [Link]());
[Link]("Last Modified : " + [Link]());
[Link]("It is a File : " + [Link]());
}
}

3.3 File Reading

22
& Writing in Java
In java, there multiple ways to read data from a file and to write data to a file. The most
commonly used ways are as follows.

 Using Byte Stream (FileInputStream and FileOutputStream)


 Using Character Stream (FileReader and FileWriter)

5.3.1 File Handling using Byte Stream


FileInputStream(inherits InputStream) class is used for reading a file .
FileOutputStream(inherits OutputStream) class is used for writing to a file .

The InputStream class has defined as an abstract class, and it has the following methods

Method Description
int available() It returns the number of bytes that can be read
from the input stream.
int read() It reads the next byte from the input stream.
int read(byte[] b) It Reads up to [Link] bytes of data from this
input stream into the byte array b.
int read(byte b[], Reads m bytes into b starting from nth byte
int n, int m)
void close() It closes the input stream and also frees any
resources connected with this input stream.
long skip(long n) Skips over n bytes from the input stream

Example:-
import [Link].*;
class Inputstream
{
public static void main(String args[])throws IOException
{
byte b[] = new byte[100];
FileInputStream f1= new FileInputStream("D:\\[Link]");
[Link]("Available bytes in the file: " +
[Link]());
[Link](b);
[Link]("Data read from the file: ");
// Convert byte array into string
String data = new String(b);
[Link](data);

// Close the input stream


23
[Link]();
}
}

The OutputStream class has defined as an abstract class, and it has the following methods.

Method Description
void write(int n) It writes byte(contained in an int) to the
output stream.
void write(byte[] b) It writes a whole byte array(b) to the output
stream.
void write(byte[] b, Writes m bytes from array b starting from nth
int n, int m) byte
void flush() It flushes the output steam by forcing out
buffered bytes to be written out.
void close() It closes the output stream and also frees any
resources connected with this output stream.

import [Link].*;
class FileOutputStreamEx
{
public static void main(String args[])throws IOException
{
FileOutputStreamfout=new FileOutputStream("[Link]");
String s="Welcome to Java io";
byte b[]=[Link]();
[Link](b);
[Link]();
[Link]();
[Link]("Success");
}
}

File Handling using Character Stream


24
In java, we can use a character stream to handle files. The character stream has the following
built-in classes to perform various operations on a file.

 FileReader - It is a built-in class in java that allows reading data from a file. This class
has implemented based on the character stream. The FileReader class provides a
method read() to read data from a file character by character.
 FileWriter - It is a built-in class in java that allows writing data to a file. This class has
implemented based on the character stream. The FileWriter class provides a
method write() to write data to a file character by character.

Example Program on Filehandling using CharacterStream


import [Link].*;
class FilewriterDemo
{
public static void main(String args[])throws IOException
{
FileWriterfw=new FileWriter("[Link]");
FileReaderfr=new FileReader("[Link]");
[Link](65);
[Link]("\n");
[Link]("Java Programming");
char ch[]={'a','b','c'};
[Link]("\n");
[Link](ch);
[Link]();
int i=[Link]();
while(i!=-1)
{
[Link]((char)i);
i=[Link]();
}
[Link]();
} }
3.4 Scanner Class
The Scanner is a built-in class in java used for read the input from the user in java
programming. The Scanner class is defined inside the [Link] package.
Hence to use the Scanner class in your program, you need to import this package as follows.

25
import [Link].*
OR

import [Link];

The Scanner class provides the easiest way to read input in a Java program.
The Scanner object breaks its input into tokens using a delimiter pattern, the default
delimiter is whitespace.
Syntax :-
Scanner scannerObject = new Scanner([Link]);

The Scanner class in java has the following methods.

Method Description
void close() Closes this scanner.
Returns true if this scanner has
booleanhasNext()
another token else false.
Returns true if the next token matches
booleanhasNext(Pattern p)
the specified pattern (p).
Returns true if the next token matches
booleanhasNext(String p) the pattern in the specified string
(p).
Returns true if the next token in this
booleanhasNextBoolean() input can be interpreted as a Boolean
value
Returns true if the next token in this
booleanhasNextByte() input can be interpreted as a byte
value.
Returns true if the next token in this
booleanhasNextDouble() input can be interpreted as a double
value.
Returns true if the next token in this
booleanhasNextFloat()
input can be interpreted as a fl oat.
Returns true if the next token in this
booleanhasNextInt()
input can be interpreted as an int.
Returns true if there is another line
booleanhasNextLine()
in the input.
Returns true if the next token in this
booleanhasNextLong() scanner’s input can be interpreted as a
long
Returns true if the next token in this
booleanhasNextShort() scanner’s input can be interpreted as a
short.
26
Returns the next complete token from
String next()
this scanner.
Returns the next token if it matches
String next(Patternpattern)
the specified pattern.
Scans the next token of the input into
booleannextBoolean()
a boolean value and returns that value.
Returns the next token of the input as
byte nextByte()
a byte.
Returns the next token of the input as
double nextdouble()
a double.
Returns the next token of the input as
float nextFlot()
a float.
Returns the next token of the input as
short nextInt()
an int
Advances this scanner past the current
short nextLine()
line and returns the input as a string
Returns the next token of the input as
short nextLong()
a long.
Returns the next token of the input as
short nextShort()
a short
Sets the delimiting pattern for scan to
Scanner useDelimiter
pattern constructed from the specified
(Stringpattern)
string.

Example:-
import [Link].*;
class ScannerInput
{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
[Link]("Enter a String");
String str=[Link]();
[Link]("Enter Integer number");
int num=[Link]();
[Link]("Enter Float number");
float real=[Link]();
[Link]("\n------------------------------------------");
[Link]("Entered String is "+ str);
[Link]("Entered Integer Number is "+ num);
[Link]("Entered Float Number is "+ real);
27
}
}

3.5 BufferedOutputStream Class


BufferedOutputStream class is used to buffer the output and enhance the performance.
Example Program
import [Link].*;
class BufferedOutputStreamExample
{
public static void main(String args[])throws IOException
{
FileOutputStreamfout=new FileOutputStream("D:\\[Link]");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to Bufferedoutput Concept";
byte b[]=[Link]();
[Link](b);
[Link]();
[Link]();
[Link]();
[Link]("Success");
}
}

28
3.6 BufferedInputStream Class
BufferedInputStream class s used for buffering the input and it supports operations to re-read
the files. It extends the functionality of FileInputStream.
BufferedInputStream class is used to provide buffering to InputStream. Instead of reading
one byte at a time, it can read a large block of data. It improves reading performance.
Methods Description
int available() Returns the number of bytes that can be read from
this input stream without blocking
Void close() Closes this input stream and releases all the
resources.
Void mark(int Similar to mark the methods of InputStream.
readlimit)
booleanmarkSupported() Tests if this input stream supports the mark and
reset methods.
int read() Similar to read of InputStreamclass.
int read(byte b[],int Reads bytes from the inputStreaminto the byte array
off, int len) starting at offset off and returns
the number of bytes read. Len specifi es the
maximum number of bytes to read.
void reset() Similar to reset method of InputStreamclass.
Long skip(long n) Similar to skip method of InputStreamclass.

Example Program :

import [Link].*;
class BufferedInputStreamEx
{
public static void main(String args[])throws IOException
{
FileInputStream fin=new FileInputStream("[Link]");
BufferedInputStream bis=new BufferedInputStream(fin);
int size=[Link]();
for(int i=0;i<size;i++)
{
[Link](i);
[Link](i);
[Link]((char)[Link]());
[Link]();
}
[Link]();
29
[Link]();
}
}

3.7 Randomly Accessing A File


In java, the [Link] package has a built-in class RandomAccessFile that enables a file to be accessed
randomly. The RandomAccessFile class has several methods used to move the cursor position in a
file.
A random access file behaves like a large array of bytes stored in a file.

Access Modes
Using the RandomAccessFile, a file may created in the following modes.

 r - Creates the file with read mode; Calling write methods will result in an IOException.
 rw - Creates the file with read and write mode.
 rwd - Creates the file with read and write mode - synchronously. All updates to file
content is written to the disk synchronously.
 rws - Creates the file with read and write mode - synchronously. All updates to file
content or meta data is written to the disk synchronously.

Methods Description
void close () Closes this random access fi le stream.
final FileChannelgetChannel() Returns the unique FileChannel object associated with this fi
le.
long getFilePointer() Returns the current offset in this fi le.
long length () Returns the length of the fi le.
int read () Reads a byte of data from this fi le.
int read (byte [] b) Reads up to [Link] bytes of data from this fi le into an array
of bytes.
int read(byte[] b, int off, int Reads up to len bytes of data from this fi le into an array of
len) bytes starting at offset off in the byte array.
final booleanreadBoolean() Reads a boolean from this fi le.
byte readByte() Reads a signed eight-bit value from this fi le.
final char readChar() Reads a character from this fi le.
final double readDouble() Reads a double from this fi le.
final float readFloat() Reads a float from this fi le.
final int readlnt () Reads a signed 32-bit integer from this fi le.
final String readLine() Reads the next line of the text from this fi le.
final long readLong() Reads a signed 64-bit integer from this fi le.

30
final short readShort() Reads a signed 16-bit number from this fi le.
void seek(long pos) Sets the fi le-pointer, measured from the beginning of this fi
le, at
which the next read or write operation occurs.
void setLength (long Sets the length of this fi le.
newLength)
int skipBytes(int n) Skips n bytes of input discarding skipped bytes.
final void write (byte [] b) Writes [Link] bytes from the specifi ed byte array to this fi
le, starting
at the current fi le pointer.
fi nal void write (byte [] b, int Writes len bytes from the specifi ed byte array starting at
off, offset off
to this fi le.
int len)
final void write(int b) Writes the specifi ed byte to this fi le.
final void Writes a boolean to the fi le as a one-byte value.
writeBoolean(boolean v)
final void writeByte(int v) Writes a byte to the fi le as a one-byte value.
final void writeBytes(String s) Writes the string to the fi le as a sequence of bytes.
final void writeChar(int v) Writes char to the fi le as a two-byte value, high byte fi rst.
final void writeChars(String s) Writes string to the fi le as a sequence of characters
final void Converts the double argument to a long using the
writeDouble(double v) doubleToLongBits
method in class Double, and then writes that long value to
the fi le as
an eight-byte quantity, high byte fi rst.
final void writeFloat (fl oat v) Converts the fl oat argument to an int using the floatTolntBits
method in class Float, and then writes that int value to the fi
le as a
four-byte quantity, high byte fi rst.
final void writelnt(int v) Writes an int to the fi le as four bytes, high byte fi rst.
final void writeLong(long v) Writes a long to the fi le as eight bytes, high byte fi rst.
final void writeShort(int v) Writes a short to the fi le as two bytes, high byte fi rst.

Example Program :
import [Link].*;
class RandomAccessFileDemo
{
public static void main(String args[]) throws IOException
{
31
[Link]("Opening the file in read write mode");
RandomAccessFileraf = new RandomAccessFile ("[Link]","rw");
[Link]([Link]());
String str = "\nContents appended using RandomAccessFile";
[Link]("Appending contents to file");
[Link]([Link]());
[Link]("Contents appended");
[Link]("Reading the contents of the fi le....");
[Link](0);
while((str = [Link]())!= null)
[Link](str);
[Link]();
}
}

32

You might also like