0% found this document useful (0 votes)
1 views52 pages

Unit 3 Java Notes-II ML

Module III covers exception handling and I/O streams in Java, detailing the mechanisms for throwing and catching exceptions, including checked and unchecked exceptions. It explains the use of keywords like try, catch, finally, throw, and throws, along with the exception class hierarchy and models of exception handling. Additionally, it discusses built-in exceptions, creating custom exceptions, and the basics of Java I/O operations.

Uploaded by

judsonasaph.al24
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)
1 views52 pages

Unit 3 Java Notes-II ML

Module III covers exception handling and I/O streams in Java, detailing the mechanisms for throwing and catching exceptions, including checked and unchecked exceptions. It explains the use of keywords like try, catch, finally, throw, and throws, along with the exception class hierarchy and models of exception handling. Additionally, it discusses built-in exceptions, creating custom exceptions, and the basics of Java I/O operations.

Uploaded by

judsonasaph.al24
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

Module III

EXCEPTION HANDLING AND I/O STREAMS

Exception handling Mechanisms exception hierarchy throwing and catching exceptions


built-in exceptions, creating own exceptions - I/O streams - Reading and Writing Console
- Reading and Writing Files
 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 can not be caught by the compiler but occurrs
at the time of program execution is called an unchecked exception.

How exceptions handled in Java?


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

Exception Types in Java

In java, exceptions are mainly categorized into two types, and they are as follows.

 Checked Exceptions
 Unchecked Exceptions

Checked Exceptions
The checked exception is an exception that is checked by the compiler during the compilation
process to confirm whether the exception is handled by the programmer or not. If it is not
handled, the compiler displays a compilation error using built-in classes.
The checked exceptions are generally caused by faults outside of the code itself like missing
resources, networking errors, and problems with threads come to mind.
The following are a few built-in classes used to handle checked exceptions in java.

 IOException
 FileNotFoundException
 ClassNotFoundException
 SQLException
 DataAccessException
 InstantiationException
 UnknownHostException

� In the exception class hierarchy, the checked exception classes are the direct children of the
Exception class.
The checked exception is also known as a compile-time exception.
Let's look at the following example program for the checked exception method.
Example - Checked Exceptions
Unchecked Exceptions

The unchecked exception is an exception that occurs at the time of program execution. The
unchecked exceptions are not caught by the compiler at the time of compilation.
The unchecked exceptions are generally caused due to bugs such as logic errors, improper use
of resources, etc.
The following are a few built-in classes used to handle unchecked exceptions in java.

 ArithmeticException
 NullPointerException
 NumberFormatException
 ArrayIndexOutOfBoundsException
 StringIndexOutOfBoundsException

� In the exception class hierarchy, the unchecked exception classes are the children of
RuntimeException class, which is a child class of Exception class.
The unchecked exception is also known as a runtime exception.
Let's look at the following example program for the unchecked exceptions.
Example - Unchecked Exceptions

Exception class hierarchy

In java, the built-in classes used to handle exceptions have the following class hierarchy.
Exception Models in Java

In java, there are two exception models. Java programming language has two models of
exception handling. The exception models that java suports are as follows.

 Termination Model
 Resumptive Model

Let's look into details of each exception model.

Termination Model

In the termination model, when a method encounters an exception, further processing in that
method is terminated and control is transferred to the nearest catch block that can handle the
type of exception encountered.

In other words we can say that in termination model the error is so critical there is no way to get
back to where the exception occurred.

Resumptive Model

The alternative of termination model is resumptive model. In resumptive model, the exception
handler is expected to do something to stable the situation, and then the faulting method is
retried. In resumptive model we hope to continue the execution after the exception is handled.

In resumptive model we may use a method call that want resumption like behavior. We may
also place the try block in a while loop that keeps re-entering the try block util the result is
satisfactory.

Uncaught Exceptions in Java

 In java, assume that, if we do not handle the exceptions in a program. In this case, when
an exception occurs in a particular function, then Java prints a exception message with
the help of uncaught exception handler.
 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.
 Java programming language has a very strong exception handling mechanism. It allow us
to handle the exception use the keywords like try, catch, finally, throw, and throws.
 When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the exception
occurs and terminates the thread.
 The Division by zero exception is one of the example for uncaught exceptions. Look at
the following code.

Example
When we execute the above code, it produce the following output for the value

a = 10 and b = 0.
In the above example code, we are not used try and catch blocks, but when the value of b is zero
the division by zero exception occurs and it caught by the default exception handler.

Try and Catch in Java

In java, the trytry and catch, both are the keywords used for exception handling.
The keyword try is used to define a block of code that will be tests the occurence of an
exception. The keyword catch is used to define a block of code that handles the exception
occured 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
can not use try without atleast one catch, and catch alone can be used (catch without try is not
allowed).
The following is the syntax of try and catch blocks.
Syntax

try{
...
code to be tested
...
}
catch(ExceptionType object){
...
code for handling the exception
...
}

Consider the following example code to illustrate try and catch blocks in Java.
Example
In the above example code, when an exception occurs in the try block the execution control
transfered to the catch block and the catch block handles it.

Multiple catch clauses


In java programming language, a try block may has 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.
The multipe catch clauses are defined when the try block contains the code that may lead to
different type of exceptions.
� The try block generates only one exception at a time, and at a time only one catch block is
executed.
� When there are multiple catch blocks, the order of catch blocks must be from the most
specific exception handler to most general.
�The catch block with Exception class handler must be defined at the last.
Let's look at the following example Java code to illustrate multiple catch clauses.
Example

Nested try statements


The java allows to write a try statement inside another try statement. A try block within another
try block is known as nested try block.
When there are nested try blocks, each try block must have one or more seperate catch blocks.
Let's look at the following example Java code to illustrate nested try statements.
Example

public class TryCatchExample {


public static void main(String[] args) {
try {
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[0] = list[2] / list[4];
try {
list[10] = 100;
}
catch(ArrayIndexOutOfBoundsException aie) {
[Link]("Problem info: ArrayIndexOutOfBoundsException has occured.");
}
}
catch(ArithmeticException ae) {
[Link]("Problem info: Value of divisor can not be ZERO.");
}
catch(Exception e) {
[Link]("Problem info: Unknown exception has occured.");
}
}
}

When we run the above code, it produce the following output.


� In case of nested try blocks, if an exception occured in the inner try block and it's catch
blocks are unable to handle it then it transfers the control to the outer try's catch block to handle
it.

throw, throws, and finally keywords in Java

In java, the keywords throw, throws, and finally are used in the exception handling concept.
Let's look at each of these keywords.

throw keyword in Java


The throw keyword is used to throw an exception instance explicitly from a try block to
corresponding catch block. That means it is used to transfer the control from try block to
corresponding catch block.
The throw keyword must be used inside the try blcok. When JVM encounters the throw
keyword, it stops the execution of try block and jump to the corresponding catch block.
�Using throw keyword only object of Throwable class or its sub classes can be thrown.
�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.

Syntax

throw instance;

Here the instace must be throwable instance and it can be created dynamically using new
operator.
Let's look at the following example Java code to illustrate throw keyword.
Example
throws keyword in Java

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
� When a method throws an exception, we must put the calling statement of method in try-
catch block.

Let's look at the following example Java code to illustrate throws keyword.

Example

import [Link];
public class ThrowsExample {
int num1, num2, result;
Scanner input = new Scanner([Link]);

void division() throws ArithmeticException {


[Link]("Enter any two numbers: ");
num1 = [Link]();
num2 = [Link]();
result = num1 / num2;
[Link](num1 + "/" + num2 + "=" + result);
}

public static void main(String[] args) {

try {
new ThrowsExample().division();
}
catch(ArithmeticException ae) {
[Link]("Problem info: " + [Link]());
}
[Link]("End of the program");
}
}

When we run the above code, it produce the following output.


finally keyword in Java

The finally keyword used to define a block that must be executed irrespective of exception
occurence.
The basic purpose of finally keyword is to cleanup resources allocated by try block, such as
closing file, closing database connection, etc.
�Only one finally block is allowed for each try block.
�Use of finally block is optional.

Let's look at the following example Java code to illustrate throws keyword.

Example
Built-in Exceptions in Java

The Java programming language has several built-in exception class that support exception
handling. Every exception class is suitable to explain certain error situations at run time.
All the built-in exception classes in Java were defined a package [Link].
Few built-in exceptions in Java are shown in the following image.
List of checked exceptions in Java

The following table shows the list of several checked exceptions.

S.
No. Exception Class with Description

1 ClassNotFoundException

It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the
specified class cannot be found in the classpath.

2 CloneNotSupportedException

Used to indicate that the clone method in class Object has been called to clone an object,
but that the object's class does not implement the Cloneable interface.

3 IllegalAccessException

It is thrown when one attempts to access a method or member that visibility qualifiers do
not allow.

4 InstantiationException

It is thrown when an application tries to create an instance of a class using the newInstance
method in class Class , but the specified class object cannot be instantiated because it is an
interface or is an abstract class.

5 InterruptedException

It is thrown when a thread that is sleeping, waiting, or is occupied is interrupted.

6 NoSuchFieldException

It indicates that the class doesn't have a field of a specified name.

7 NoSuchMethodException

It is thrown when some JAR file has a different version at runtime that it had at compile
time, a NoSuchMethodException occurs during reflection when we try to access a method
that does not exist.
List of unchecked exceptions in Java
The following table shows the list of several unchecked exceptions.

S.
No. Exception Class with Description

1 ArithmeticException

It handles the arithmetic exceptions like dividion by zero

2 ArrayIndexOutOfBoundsException

It handles the situations like an array has been accessed with an illegal index. The index
is either negative or greater than or equal to the size of the array.

3 ArrayStoreException

It handles the situations like when an attempt has been made to store the wrong type of
object into an array of objects

4 AssertionError

It is used to indicate that an assertion has failed

5 ClassCastException

It handles the situation when we try to improperly cast a class from one type to another.

6 IllegalArgumentException

This exception is thrown in order to indicate that a method has been passed an illegal or
inappropriate argument.

7 IllegalMonitorStateException

This indicates that the calling thread has attempted to wait on an object's monitor, or has
attempted to notify other threads that wait on an object's monitor, without owning the
specified monitor.

8 IllegalStateException

It signals that a method has been invoked at an illegal or inappropriate time.


S.
No. Exception Class with Description

9 IllegalThreadStateException

It is thrown by the Java runtime environment, when the programmer is trying to modify
the state of the thread when it is illegal.

10 IndexOutOfBoundsException

It is thrown when attempting to access an invalid index within a collection, such as an


array , vector , string , and so forth

11 NegativeArraySizeException

It is thrown if an applet tries to create an array with negative size.

12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.

13 NumberFormatException

It is thrown when we try to convert a string into a numeric value such as float or integer,
but the format of the input string is not appropriate or illegal.

14 SecurityException
It is thrown by the Java Card Virtual Machine to indicate a security violation.

15 StringIndexOutOfBounds

It is thrown by the methods of the String class, in order to indicate that an index is either
negative, or greater than the size of the string itself.

16 UnsupportedOperationException

It is thrown to indicate that the requested operation is not supported.


Creating Own Exceptions in Java

 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.
 Let's look at the following Java code that illustrates the creation of user-defined
exception.
Example

import [Link];
class NotEligibleException extends Exception{
NotEligibleException(String msg){
super(msg); } }
class VoterList{
int age;
VoterList(int age){ [Link] = age; }
void checkEligibility() {
try {
if(age < 18) {
throw new NotEligibleException("Error: Not eligible for vote due to under age.");
}
[Link]("Congrates! You are eligible for vote.");
}
catch(NotEligibleException nee) { [Link]([Link]()); } }
public static void main(String args[]) {
Scanner input = new Scanner([Link]); [Link]("Enter your age in years: ");
int age = [Link](); VoterList person = new VoterList(age);
[Link]();
} }

Multithreading in java
Java I/O (Input/Output) is a collec on of classes and streams in the [Link] package that handle
reading data from sources (like files, keyboard, or network) and wri ng data to des na ons (like
files, console or sockets). It provides both byte and character streams to support all types of
data.
 In java, the stream-based IO operations are performed using two separate streams input
stream and output stream.
 The input stream is used for input operations, and the output stream is used for output
operations.
 The java stream is composed of bytes.
 In Java, every program creates 3 streams automatically, and these streams are attached to
the console.
 [Link]: standard output stream for console output operations.
 [Link]: standard input stream for console input operations.
 [Link]: standard error stream for console error output operations.
 The Java streams support many different kinds of data, including simple bytes, primitive
data types, localized characters, and objects.

Java provides two types of streams, and they are as follows.

 Byte Stream
 Character Stream

The following picture shows how streams are categorized, and various built-in classes used by
the java IO system.
Both character and byte streams essentially provides a convenient and efficient way to handle
data streams in Java.

Byte Stream in java

 In java, the byte stream is an 8 bits carrier.


 The byte stream in java allows us to transmit 8 bits of data.
 In Java 1.0 version all IO operations were byte oriented, there was no other stream
(character stream).
 The java byte stream is defined by two abstract
classes, InputStream and OutputStream.
 The InputStream class used for byte stream based input operations, and the OutputStream
class used for byte stream based output operations.
 The InputStream and OutputStream classes have several concreate classes to perform
various IO operations based on the byte stream.
 The following picture shows the classes used for byte stream operations.
InputStream class

The InputStream class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.

[Link]. Method with Description

1 int available()

It returns the number of bytes that can be read from the input stream.

2 int read()

It reads the next byte from the input stream.

3 int read(byte[] b)
It reads a chunk of bytes from the input stream and store them in its byte array, b.

4 void close()

It closes the input stream and also frees any resources connected with this input stream.
OutputStream class
The OutputStream class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.

[Link]. Method with Description

1 void write(int n)

It writes byte(contained in an int) to the output stream.

2 void write(byte[] b)

It writes a whole byte array(b) to the output stream.

3 void flush()

It flushes the output steam by forcing out buffered bytes to be written out.

4 void close()
It closes the output stream and also frees any resources connected with this output stream.

Reading data using BufferedInputStream


We can use the BufferedInputStream class to read data from the console. The
BufferedInputStream class use a method read( ) to read a value from the console, or file, or
socket.
Let's look at an example code to illustrate reading data using BufferedInputStream.
Example 1 - Reading from console
Example 2 - Reading from a file
Writing data using BufferedOutputStream
We can use the BufferedOutputStream class to write data into the console, file, socket. The
BufferedOutputStream class use a method write( ) to write data.
Let's look at an example code to illustrate writing data into a file using BufferedOutputStream.
Example - Writing data into a file

Character Stream in java

 In java, when the IO stream manages 16-bit Unicode characters, it is called a character
stream.
 The unicode set is basically a type of character set where each character corresponds to a
specific numeric value within the given character set, and every programming language
has a character set.
 In java, the character stream is a 16 bits carrier. The character stream in java allows us to
transmit 16 bits of data.
 The character stream was introduced in Java 1.1 version. The charater stream
 The java character stream is defined by two abstract classes, Reader and Writer. The
Reader class used for character stream based input operations, and the Writer class used
for charater stream based output operations.
 The Reader and Writer classes have several concreate classes to perform various IO
operations based on the character stream.
The following picture shows the classes used for character stream operations.

Reader class
The Reader class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.

[Link]. Method with Description

1 int read()

It reads the next character from the input stream.

2 int read(char[] cbuffer)

It reads a chunk of charaters from the input stream and store them in its byte array,
cbuffer.
[Link]. Method with Description

3 int read(char[] cbuf, int off, int len)

It reads charaters into a portion of an array.

4 int read(CharBuffer target)


It reads charaters into into the specified character buffer.

5 String readLine()

It reads a line of text. A line is considered to be terminated by any oneof a line feed
('\n'), a carriage return ('\r'), or a carriage returnfollowed immediately by a linefeed.

6 boolean ready()

It tells whether the stream is ready to be read.

7 void close()

It closes the input stream and also frees any resources connected with this input stream.

Writer class
The Writer class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.

[Link]. Method with Description

1 void flush()

It flushes the output steam by forcing out buffered bytes to be written out.

2 void write(char[] cbuf)

It writes a whole array(cbuf) to the output stream.

3 void write(char[] cbuf, int off, int len)

It writes a portion of an array of characters.


[Link]. Method with Description

4 void write(int c)

It writes single character.

5 void write(String str)

It writes a string.

6 void write(String str, int off, int len)

It writes a portion of a string.

7 Writer append(char c)

It appends the specified character to the writer.

8 Writer append(CharSequence csq)


It appends the specified character sequence to the writer

9 Writer append(CharSequence csq, int start, int end)

It appends a subsequence of the specified character sequence to the writer.

10 void close()

It closes the output stream and also frees any resources connected with this output
stream.

Reading data using BufferedReader


We can use the BufferedReader class to read data from the console. The BufferedInputStream
class needs InputStreamReaderclass. The BufferedReader use a method read( ) to read a value
from the console, or file, or socket.

Let's look at an example code to illustrate reading data using BufferedReader.


Example 1 - Reading from console

Example 2 - Reading from a file


Writing data using FileWriter
We can use the FileWriter class to write data into the file. The FileWriter class use a method
write( ) to write data.
Let's look at an example code to illustrate writing data into a file using FileWriter.
Example - Writing data into a file

Console IO Operations in Java


Reading console input in java
In java, there are three ways to read console input. Using the 3 following ways, we can read
input data from the console.

 Using BufferedReader class


 Using Scanner class
 Using Console class

Let's explore the each method to read data with example.


1. Reading console input using BufferedReader class in java
Reading input data using the BufferedReader class is the traditional technique. This way of the reading method
is used by wrapping the [Link] (standard input stream) in an InputStreamReader which is wrapped in
a BufferedReader, we can read input from the console.
The BufferedReader class has defined in the [Link] package.
Consider the following example code to understand how to read console input using BufferedReader class.

Example

2. Reading console input using Scanner class in java


Reading input data using the Scanner class is the most commonly used method. This way of the reading
method is used by wrapping the [Link] (standard input stream) which is wrapped in a Scanner, we can read
input from the console.
The Scanner class has defined in the [Link] package.
Consider the following example code to understand how to read console input using Scanner class.

Example
3. Reading console input using Console class in java
Reading input data using the Console class is the most commonly used method. This class was introduced in
Java 1.6 version.
The Console class has defined in the [Link] package.
Consider the following example code to understand how to read console input using Console class.

Example

import [Link].*;
public class ReadingDemo {
public static void main(String[] args) {
String name;
Console con = [Link]();
if(con != null) {
name = [Link]("Please enter your name : ");
[Link]("Hello, " + name + "!!");
}
else {
[Link]("Console not available.");
}
}
}

Writing console output in java


In java, there are two methods to write console output. Using the 2 following methods, we can
write output data to the console.

 Using print() and println() methods


 Using write() method

Let's explore the each method to write data with example.

 Writing console output using print() and println() methods


 The PrintStream is a bult-in class that provides two methods print() and println() to write
console output. The print() and println() methods are the most widely used methods for
console output.
 Both print() and println() methods are used with [Link] stream.
 The print() method writes console output in the same line. This method can be used with
console output only.
 The println() method writes console output in a separete line (new line). This method can
be used with console ans also with other output sources.
Let's look at the following code to illustrate print() and println() methods.
Example
2. Writing console output using write() method
Alternatively, the PrintStream class provides a method write() to write console output.
The write() method take integer as argument, and writes its ASCII equalent character on to the
console, it also acept escape sequences.
Let's look at the following code to illustrate write() method.
Example
File class in Java
 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.

[Link]. Constructor with Description

1 File(String pathname)

It creates a new File instance by converting the givenpathname string into an abstract
pathname. If the given string isthe empty string, then the result is the empty abstract
pathname.

2 File(String parent, String child)


It Creates a new File instance from a parent abstractpathname and a child pathname
string. If parent is null then the new File instance is created as if by invoking thesingle-
argument File constructor on the given child pathname string.
[Link]. Constructor with Description

3 File(File parent, String child)


It creates a new File instance from a parent abstractpathname and a child pathname
string. If parent is null then the new File instance is created as if by invoking thesingle-
argument File constructor on the given child pathname string.

4 File(URI uri)
It creates a new File instance by converting the given file: URI into an abstract
pathname.

The File class in java has the following methods.

[Link]. Methods with Description

1 String getName()

It returns the name of the file or directory that referenced by the current File object.

2 String getParent()
It returns the pathname of the pathname's parent, or null if the pathname does not name
a parent directory.

3 String getPath()
It returns the path of curent File.

4 File getParentFile()
It returns the path of the current file's parent; or null if it does not exist.

5 String getAbsolutePath()
It returns the current file or directory path from the root.

6 boolean isAbsolute()
It returns true if the current file is absolute, false otherwise.

7 boolean isDirectory()
It returns true, if the current file is a directory; otherwise returns false.

8 boolean isFile()
It returns true, if the current file is a file; otherwise returns false.
[Link]. Methods with Description

9 boolean exists()
It returns true if the current file or directory exist; otherwise returns false.

10 boolean canRead()
It returns true if and only if the file specified exists and can be read by the application;
false otherwise.

11 boolean canWrite()
It returns true if and only if the file specified exists and the application is allowed to
write to the file; false otherwise.

12 long length()
It returns the length of the current file.

13 long lastModified()
It returns the time that specifies the file was last modified.

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

15 boolean delete()
It deletes the file or directory. And returns true if and only if the file or directory is
successfully deleted; false otherwise.

16 void deleteOnExit()
It sends a requests that the file or directory needs be deleted when the virtual machine
terminates.

17 boolean mkdir()
It returns true if and only if the directory was created; false otherwise.

18 boolean mkdirs()
It returns true if and only if the directory was created, along with all necessary parent
directories; false otherwise.

19 boolean renameTo(File dest)


It renames the current file. And returns true if and only if the renaming succeeded; false
[Link]. Methods with Description

otherwise.

20 boolean setLastModified(long time)


It sets the last-modified time of the file or directory. And returns true if and only if the
operation succeeded; false otherwise.

21 boolean setReadOnly()
It sets the file permission to only read operations; Returns true if and only if the
operation succeeded; false otherwise.

22 String[] list()
It returns an array of strings containing names of all the files and directories in the
current directory.

23 String[] list(FilenameFilter filter)


It returns an array of strings containing names of all the files and directories in the
current directory that satisfy the specified filter.

24 File[] listFiles()
It returns an array of file references containing names of all the files and directories in
the current directory.

25 File[] listFiles(FileFilter filter)


It returns an array of file references containing names of all the files and directories in
the current directory that satisfy the specified filter.

26 boolean equals(Object obj)


It returns true if and only if the argument is not null and is an abstract pathname that
denotes the same file or directory as this abstract pathname.

27 int compareTo(File pathname)


It Compares two abstract pathnames lexicographically. It returns zero if the argument is
equal to this abstract pathname, a value less than zero if this abstract pathname is
lexicographically less than the argument, or a value greater than zero if this abstract
pathname is lexicographically greater than the argument.

28 int compareTo(File pathname)


Compares this abstract pathname to another object. Returns zero if the argument is
[Link]. Methods with Description

equal to this abstract pathname, a value less than zero if this abstract pathname is
lexicographically less than the argument, or a value greater than zero if this abstract
pathname is lexicographically greater than the argument.

Let's look at the following code to illustrate file operations.


Example

import [Link].*;
public class FileClassTest {

public static void main(String args[]) {


File f = new File("C:\\Raja\\[Link]");

[Link]("Executable File : " + [Link]());


[Link]("Name of the file : " + [Link]());
[Link]("Path of the file : " + [Link]());
[Link]("Parent name : " + [Link]());
[Link]("Write mode : " + [Link]());
[Link]("Read mode : " + [Link]());
[Link]("Existance : " + [Link]());
[Link]("Last Modified : " + [Link]());
[Link]("Length : " + [Link]());
//[Link]()
//[Link]();
//[Link]()
}

}
Let's look at the following java code to list all the files in a directory including the files present
in all its subdirectories.
Example

import [Link];
import [Link].*;
public class ListingFiles {
public static void main(String[] args) {
String path = null;
Scanner read = new Scanner([Link]);
[Link]("Enter the root directory name: ");
path = [Link]() + ":\\";
File f_ref = new File(path);
if (!f_ref.exists()) {
printLine();
[Link]("Root directory does not exists!");
printLine();
} else {
String ch = "y";
while ([Link]("y")) {
printFiles(path);
[Link]("Do you want to open any sub-directory
(Y/N): ");
ch = [Link]().toLowerCase();
if ([Link]("y")) {
[Link]("Enter the sub-directory name: ");
path = path + "\\\\" + [Link]();
File f_ref_2 = new File(path);
if (!f_ref_2.exists()) {
printLine();
[Link]("The sub-directory does not
exists!");
printLine();
int lastIndex = [Link]("\\");
path = [Link](0, lastIndex);
}
}
}
}
[Link]("***** Program Closed *****");
}

public static void printFiles(String path) {


[Link]("Current Location: " + path);
File f_ref = new File(path);
File[] filesList = f_ref.listFiles();
for (File file : filesList) {
if ([Link]())
[Link]("- " + [Link]());
else
[Link]("> " + [Link]());
}
}

public static void printLine() {


[Link]("----------------------------------------");
}
}
File Reading & 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)

Let's look each of these ways.

File Handling using Byte Stream


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

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

Let's look at the following example program that reads data from a file and writes the same to
another file using FileInoutStream and FileOutputStream classes.
Example

import [Link].*;
public class FileReadingTest {

public static void main(String args[]) throws IOException {


FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("C:\\Raja\\[Link]");
out = new FileOutputStream("C:\\Raja\\[Link]");

int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
[Link]("Reading and Writing has been success!!!");
}
catch(Exception e){
[Link](e);
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}

File Handling using Character Stream


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.

Let's look at the following example program that reads data from a file and writes the same to
another file using FIleReader and FileWriter classes.

Example
import [Link].*;
public class FileIO {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("C:\\Raja\\[Link]");
out = new FileWriter("C:\\Raja\\[Link]");

int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
[Link]("Reading and Writing in a file is done!!!");
}
catch(Exception e) {
[Link](e);
}
finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}

RandomAccessFile in Java
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.

RandomAccessFile Constructors
The RandomAccessFile class in java has the following constructors.

[Link]. Constructor with Description

1 RandomAccessFile(File fileName, String mode)

It creates a random access file stream to read from, and optionally to write to, the file specified
argument.

2 RandomAccessFile(String fileName, String mode)

It creates a random access file stream to read from, and optionally to write to, a file with th
fileName.

Access Modes
Using the RandomAccessFile, a file may created in th 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.

RandomAccessFile methods
The RandomAccessFile class in java has the following methods.

[Link]. Methods with Description

1 int read()

It reads byte of data from a file. The byte is returned as an integer in the range 0-255.
[Link]. Methods with Description

2 int read(byte[] b)

It reads byte of data from file upto [Link], -1 if end of file is reached.

3 int read(byte[] b, int offset, int len)

It reads bytes initialising from offset position upto [Link] from the buffer.

4 boolean readBoolean()

It reads a boolean value from from the file.

5 byte readByte()

It reads signed eight-bit value from file.

6 char readChar()
It reads a character value from file.

7 double readDouble()

It reads a double value from file.

8 float readFloat()
It reads a float value from file.

9 long readLong()

It reads a long value from file.

10 int readInt()

It reads a integer value from file.

11 void readFully(byte[] b)

It reads bytes initialising from offset position upto [Link] from the buffer.
[Link]. Methods with Description

12 void readFully(byte[] b, int offset, int len)

It reads bytes initialising from offset position upto [Link] from the buffer.

13 String readUTF()

t reads in a string from the file.

14 void seek(long pos)

It sets the file-pointer(cursor) measured from the beginning of the file, at which the
next read or write occurs.

15 long length()

It returns the length of the file.

16 void write(int b)

It writes the specified byte to the file from the current cursor position.

17 void writeFloat(float v)

It converts the float argument to an int using the floatToIntBits method in class Float,
and then writes that int value to the file as a four-byte quantity, high byte first.

18 void writeDouble(double v)

It converts the double argument to a long using the doubleToLongBits method in class
Double, and then writes that long value to the file as an eight-byte quantity, high byte
first.

Let's look at the following example program.


Example

import [Link].*;

public class RandomAccessFileDemo


{
public static void main(String[] args)
{
try
{
double d = 1.5;
float f = 14.56f;

// Creating a new RandomAccessFile - "F2"


RandomAccessFile f_ref = new RandomAccessFile("C:\\Raja\\[Link]", "rw");

// Writing to file
f_ref.writeUTF("Hello, Good Morning!");

// File Pointer at index position - 0


f_ref.seek(0);

// read() method :
[Link]("Use of read() method : " + f_ref.read());

f_ref.seek(0);

byte[] b = {1, 2, 3};

// Use of .read(byte[] b) method :


[Link]("Use of .read(byte[] b) : " + f_ref.read(b));
// readBoolean() method :
[Link]("Use of readBoolean() : " + f_ref.readBoolean());

// readByte() method :
[Link]("Use of readByte() : " + f_ref.readByte());

f_ref.writeChar('c');
f_ref.seek(0);

// readChar() :
[Link]("Use of readChar() : " + f_ref.readChar());

f_ref.seek(0);
f_ref.writeDouble(d);
f_ref.seek(0);

// read double
[Link]("Use of readDouble() : " + f_ref.readDouble());

f_ref.seek(0);
f_ref.writeFloat(f);
f_ref.seek(0);

// readFloat() :
[Link]("Use of readFloat() : " + f_ref.readFloat());

f_ref.seek(0);
// Create array upto [Link]
byte[] arr = new byte[(int) f_ref.length()];
// readFully() :
f_ref.readFully(arr);

You might also like