UNIT-III
Dealing Exceptions and I/O
Exception Handling: Fundamentals of exception handling, benefits of exception
handling, Exception types, Termination or presumptive models, Uncaught exceptions,
using try and catch, multiple catch clauses, nested try statements, exception hierarchy,
throw, throws and finally, built in Exceptions, Custom exceptions, Throwable Class.
Java I/O–Byte streams, character streams, Scanner class, Console class, Serialization and
Serializable interface, File class.
Introduction:
Types of Errors:
1.Compile-time error(Ex:Syntactical Errors)
2.Runtime Errors(Exception)
Exception:
The runtime error which stop the normal flow of the program is called “Exception”.(or)
Exception is an abnormal condition .
In Java, an exception is an event that disrupts the
Exception Handling in Java
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
normal flow of the program. It is an object which is thrown at runtime.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application.
An exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in your program and there occurs an exception at statement 5,
the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we
perform exception handling, the rest of the statement will be executed. That is why we use
exception handling in Java.
Types of Java Exceptions
There are mainly two types of exceptions:
1) Checked Exception
2) Unchecked Exception
3) Error
1) Checked Exception
A checked exception is an exception that is checked (notified) by the compiler at
compilation-time, these are also called as “compile time exceptions”.
These exceptions cannot simply be ignored, the programmer should take care of (handle)
these exceptions.
For example if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the
compiler prompts the programmer to handle the exception.
Ex: IOException, SQLException etc. Checked exceptions are checked at compile-time.
Example
import java.io.*;
import java.io.FileReader;
public class FilenotFound_Demo
{
public static void main(String args[])
{
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
Output
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught
or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error
2) Unchecked Exception
An unchecked exception is an exception that occurs at the time of execution. These are also
called as “Runtime Exceptions”.
Example: These include programming bugs, such as logic errors or improper use of an API.
Runtime exceptions are ignored at the time of compilation.
If you have declared an array of size 5 in your program, and trying to call the 6 th element of the
array then an ArrayIndexOutOfBoundsException exception occurs.
Example
public class Unchecked_Demo {
public static void main(String args[])
{
int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
Ex:ArithmeticException,NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything about
an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the
time of compilation.
Ex: OutOfMemoryError, VirtualMachineError, AssertionError etc.
Hierarchy of Java Exception classes
Exception Hierarchy
All exception classes are subtypes of the java.lang.Exception class. The exception class
is a subclass of the Throwable class. Other than the exception class there is another
subclass called Error which is derived from the Throwable class.
Errors are abnormal conditions that happen in case of severe failures, these are not
handled by the Java programs. Errors are generated to indicate errors generated by the
runtime environment. Example: JVM is out of memory. Normally, programs cannot
recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException
Class.
Exception Handling Mechanisms:
To handle the Exception we have 5 exception handling mechanisms.They are
1.try
2.catch
3.throw
4.throws
5.finally
1.try :The code which will raise the exception will be written in try block.
Syntax:
try
//Set of stmts which raise the exception
Ex:
try
int a=10,b=0;
int c=a/b;
2.catch:
The exception which is raised in try block will be catched by the catch block.
Syntax:
catch(Exceptiontype object)
//stmts
Ex:
catch(ArithmeticException e)
{
System.out.println(“The value of b should be greater than zero”);
3.Throw: Whenever exception raised if we want to handle the exception
by ourself then we can throw using “throw” statement then we
can handle it.
Syntax:
throw new ExceptionObject(Parameters);
Ex: throw new MyException();
4.Throws: Whenever exception raised if we don’t want to handle then by
using “throws” statement we can pass it to java compiler.
Syntax:
throws ExceptionClass;
5.finally: A finally block contains all the crucial statements that must be executed whether
exception occurs or not.
The statements present in this block will always execute regardless of whether exception
occurs in try block or not
Syntax:
finally
//Set of statements
Example:
class Example
{
public static void main(String args[])
try
int num=121/0;
System.out.println(num);
catch(ArithmeticException e)
System.out.println("Number should not be divided by zero");
/* Finally block will always execute
* even if there is no exception in try block
*/
finally
System.out.println("This is finally block");
System.out.println("Out of try-catch-finally");
Output:
Number should not be divided by zero
This is finally block
Out of try-catch-finally
Example2:
Program on exception handling:
class ExceptionHand
void Division()
try
int a=10,b=0;
if(b==0)
throw new ArithmeticException();
else
System.out.println("Division="+(a/b));
catch(ArithmeticException ae)
System.out.println("ArithmeticException caught");
void ArrayBounds()
{
try
int[] Arr=new int[5];
System.out.println(Arr[6]);
catch(ArrayIndexOutOfBoundsException e)
System.out.println("ArrayoutofboundsException caught");
class ExceptionHandDemo
public static void main(String args[])
ExceptionHand obj1=new ExceptionHand();
obj1.Division();
obj1.ArrayBounds();
}
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 supports 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
import java.util.Scanner;
public class UncaughtExceptionExample {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.println("Enter the a and b values: ");
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);
}
}
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.
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 java.lang.
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.
9 IllegalThreadStateException
S. No. Exception Class with Description
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.
Custom Exceptions In Java(creating own exception subclasses)
So far we have discussed all the exceptions that are built-in or provided by Java
language. Apart from these exceptions, we can also define our own exceptions. These
are called “Custom exceptions” or “user-defined exceptions”.
Using custom exceptions, we can define our exceptions as per our needs.
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.
The following example shows the custom exception that we defined for an Integer value.
//custom exception definition
Import java.io.*;
class InvalidValueException extends Exception
InvalidValueException(String s)
super(s);
class Main
static void validate(int int_val)throws IOException, InvalidValueException
if(int_val<10)
throw new InvalidValueException("Invalid value");
else
System.out.println("This is valid integer");
public static void main(String args[])
try
validate(9);
//validate(12);
catch(Exception m)
System.out.println("Exception occured: "+m);
System.out.println("Code after Exception");
Output
Example2:
import java.util.Scanner;
class NotEligibleException extends Exception{
NotEligibleException(String msg){
super(msg);
}
}
class VoterList{
int age;
VoterList(int age){
this.age = age;
}
void checkEligibility() {
try {
if(age < 18) {
throw new NotEligibleException("Error: Not eligible for vote due to under age.");
}
System.out.println("Congrates! You are eligible for vote.");
}
catch(NotEligibleException nee) {
System.out.println(nee.getMessage());
}
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your age in years: ");
int age = input.nextInt();
VoterList person = new VoterList(age);
person.checkEligibility();
}
}
When we run this code, it produce the following output.
Throwable Class in Java
The Throwable class is the superclass of every error and exception in the Java
language. Only objects that are one of the subclasses this class are thrown by any “Java
Virtual Machine” or may be thrown by the Java throw statement.
Throwable class is the root class of Java Exception Hierarchy and is inherited by two
subclasses:
1.Exception
2.Error
The throwable class implements Serializable Interface and the direct known classes to
Throwable are Error and Exception.
Throwable contains a snapshot of the execution stack of its thread at the time it was
created. It can also contain a message string that gives more information about the
error. It can also suppress(an exception that is thrown but somehow ignored) other
throwables from being propagated.
If a user wants to create his own, custom throwable, then he/she can extend Throwable
class.
Example:
Class MyThrowable extends Throwable{
//Here the user can create his own custom throwable
}
Class GFG{
Public void test() throws MyThrowable{
// the custom throwable created can be used as follows
throw new MyThrowable();
}
}
The class declaration for java.lang.Throwable class is as follows:
public class Throwable extends Object
implements Serializable
Constructors: Any class can have any one of the three or all the three types of
constructors. They are default, parameterized and non-parameterized constructors. This
class primarily has the following constructors defined:
Public Constructors
1. Throwable(): It is a non-parameterized constructor which constructs a new
Throwable with null as its detailed message.
2. Throwable(String message): It is a parameterized constructor which constructs
a new Throwable with the specific detailed message.
3. Throwable(String message, Throwable cause): It is a parameterized
constructor which constructs a new Throwable with the specific detailed
message and a cause.
4. Throwable(Throwable cause): It is a parameterized constructor which
constructs a new Throwable with the specific cause and a detailed message of
the cause by converting the case to the String using toString() method.
Protected constructors
1. Throwable(String message, Throwable cause, boolean enableSuppression, boolean
writableStackTrace):It Constructs a new throwable with the specified detail message,
cause, suppression enabled or disabled, and writable stack trace enabled or disabled.
The parameters are:-
message – the detail message.
cause – the cause. (A null value is permitted, and indicates that the cause is nonexistent or
unknown.)
enableSuppression – whether or not suppression is enabled or disabled
writableStackTrace – whether or not the stack trace should be writable.
Methods: Apart from the above mentioned constructors, there are also many predefined
methods available in the throwable class. They are:
1. addSuppressed(Throwable exception): This method appends the specified exception to
the exceptions that were suppressed in order to deliver this exception.
Syntax:
Public final void addSuppressed(Throwable exception)
Returns: This method does not returns anything.
2. fillInStackTrace():Fills in the execution stack trace. This method records information
about the current state of the stack frames for the current thread within the current
Throwable object.
Syntax:
public Throwable fillInStackTrace ()
Returns: a reference to the current Throwable instance.
3. getCause(): It returns the cause that was supplied via one of the constructors requiring a
Throwable , or that was set after creation with the initCause() method.
Syntax:
public Throwable getCause ()
Returns: the cause of current Throwable. If the cause is nonexistent or unknown, it returns
null.
4. getLocalizedMessage(): This method creates a localized description of current
Throwable.
Syntax:
public String getLocalizedMessage ()
Returns: The localized description of current Throwable
5. getMessage():Returns the detail message string of current throwable.
Syntax:
public String getMessage ()
Returns: the detailed message string of current Throwable instance( may also return null)
6. getStackTrace(): This method provides programmatic access to the stack trace
information printed by printStackTrace(). It returns an array of stack trace elements, each
representing one stack frame. The zeroth element of the array (assume that the array’s
length is non-zero) is the last method invocation in the sequence. It also represents as the
top of the stack and is the point at which this throwable was created and thrown. The last
element of the array (assuming the array’s length is non-zero) is the first method invocation
in the sequence and it represents the bottom of the stack.
Syntax:
public StackTraceElement[] getStackTrace ()
Returns: an array of stack trace elements representing the stack trace related to current
Throwable.
7. getSuppressed():Returns an array containing all of the exceptions that were suppressed,
in order to deliver this exception. If no exceptions were suppressed or suppression is
disabled, an empty array is returned.
Syntax: public final Throwable[] getSuppressed ()
Returns: an array containing all of the exceptions that were suppressed to deliver this
exception.
8. initCause(Throwable cause):Initializes the cause of current Throwable to the specified
value. This method can be called at most once. It is generally called from within the
constructor, or immediately after creating the throwable.
Syntax: public Throwable initCause (Throwable cause)
Parameters:
Throwable cause- the cause of current Throwable.
Throws:
1.IllegalArgumentException: This exception is thrown if cause is the current throwable,
because a throwable cannot be its own cause.
2. IllegalStateException: It occurs if this method has already been called on current
throwable.
Returns: a reference to current Throwable instance.
9. printStackTrace():Prints the current throwable and its backtrace to the standard error
stream.
Syntax: public void printStackTrace ()
Returns: This method returns nothing.
10. printStackTrace(PrintWriter s):Prints current throwable and its backtrace to the
specified print writer.
Syntax: public void printStackTrace (PrintWriter s)
Parameters: PrintWriter- It is the PrintWriter to use for output
Returns: This method returns nothing.
11. printStackTrace(PrintStream s):Prints current throwable and its backtrace to the
specified print stream.
Syntax: public void printStackTrace (PrintStream s)
Parameters: PrintStream- It is the PrintStream to use for output
Returns: This method returns nothing.
12. setStackTrace(StackTraceElement[] stackTrace):This method sets the stack trace
elements that will be returned by getStackTrace() and printed by printStackTrace() and
related methods.
Syntax: public void setStackTrace (StackTraceElement[] stackTrace)
Parameter: StackTraceElement- These are the stack trace elements to be associated with
current Throwable.
Throws:
NullPointerException- if stackTrace is null or if any of the elements of stackTrace are null
Returns:
This method returns nothing.
13. toString(): This method returns a short description of current throwable.
Syntax: public String toString ()
Returns: a string representation of current throwable.
Below program demonstrates the toString() method of Throwable class:
Java
// Java program to demonstrate
// the toString() Method.
import java.io.*;
class GFG {
// Main Method
public static void main(String[] args)
throws Exception
{
try {
testException();
}
catch (Throwable e) {
// Print using tostring()
System.out.println("Exception: "
+ e.toString());
}
}
// Method which throws Exception
public static void testException()
throws Exception
{
throw new Exception(
"New Exception Thrown");
}
}
Output:
Exception:
java.lang.Exception:
New Exception Thrown
Below program demonstrate the getMessage() method of java.lang.Throwable Class:
Java
// Java program to demonstrate
// the getMessage() Method.
import java.io.*;
class GFG {
// Main Method
public static void main(String[] args)
throws Exception
{
try {
// Divide the numbers
divide(2, 0);
}
catch (ArithmeticException e) {
System.out.println(
"Message String = "
+ e.getMessage());
}
}
// Method which divides two numbers
public static void divide(int a, int b)
throws ArithmeticException
{
int c = a / b;
System.out.println("Result:" + c);
}
}
Output:
Message String = / by zero
Multiple Catch Blocks in Java
Java Multi-catch block
A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
Points to remember
At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Flowchart of Multi-catch Block
Example
Let's see a simple example of java multi-catch block.
MultipleCatchBlock.java
public class MultipleCatchBlock{
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Java Nested try block
In Java, using a try block inside another try block is permitted. It is called as nested
try block.
Every statement that we enter a statement in try block, context of that exception is
pushed onto the stack.
For example, the inner try block can be used to
handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).
Why to use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}
}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
Example
Let's see an example where we place a try block within another try block for two different
exceptions.te
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}
//inner try block 2
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
Output:
Note:
When any try block does not have a catch block for a particular exception, then the catch
block of the outer (parent) try block are checked for that exception, and if it matches, the
catch block of outer try block is executed.
If none of the catch block specified in the code is unable to handle the exception, then the
Java runtime system will handle the exception. Then it displays the system generated
message for that exception.
I/O Streams in Java
Stream
Def:A logical connection between java program and a file(to which
we can send the data and from which we can read the data) is called
“Stream”.
Java I/O (Input and Output) is also known as file handling. It is
used to process input (such as text or binary files) and the output
(java files). java.io package contains all the classes to perform
input and output operations.
Why We Need IO Streams in Java?
In day-to-day work, we do not enter the input into the programs
manually. Also, the result of the program needs to be stored
somewhere for further use.
So, IO streams in Java provide us with input and output streams that
help us to extract data from the files and write the data into the files.
Normally, we can create, delete, and edit files using Java.io.
In short, all the file manipulation is done using Java IO streams.
Types of Streams in Java
The stream method helps to sequentially access a file. There are two
types of streams in Java-
1. Byte Stream and
2. Character Stream.
Byte streams in Java are used to perform input and output operations
of 8-bit bytes while the Character stream is used to perform input and
output operations for 16-bits Unicode.
Character streams are useful in reading or writing text files which are
processed character by character. Byte Streams are useful to
read/write data from raw binary files.
An I/O (Input/Output) stream is used to represent an input source or
an output destination. It can represent many kinds of sources and
destinations like disc files (systems that manage data on permanent
storage devices eg. hard disc or magnetic disc) or devices.
Byte Streams(or)Binary Streams in Java
Byte streams are used to perform input and output of 8-bit bytes.
They are used to read bytes from the input stream and write bytes to
the output stream. Mostly, they are used to read or write raw binary
data.
Java provides many byte stream classes, but the most common ones
are-
FileInputStream- This class is used to read data from a file/source.
The FileInputStream class has constructors which we can use to
create an instance of the FileInputStream class.
Syntax:
FileInputStream sourceStream = new FileInputStream("path_to_file");
FileOutputStream- This class is used to write data to the destination.
The following is the constructor to create an instance of the
FileOutputStream class.
Syntax:
FileOutputStream targetStream = newFileOutputStream("path_to_file");
Stream class Description
BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStream Used for Buffered Output Stream.
DataInputStream Contains method for reading java standard
datatype
DataOutputStream An output stream that contain method for
writing java standard data type
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that
contain print() and println() method
These classes define several key methods.
Two most important are
read() : reads byte of data.
write() : Writes byte of data.
Example of Byte Stream
import java.io.*;
public class ByteStreamExample
{
public static void main(String[] args) throws IOException
{
FileInputStream sourceStream = null;
FileOutputStream targetStream = null;
try
{
sourceStream = new FileInputStream("source.txt");
targetStream = new FileOutputStream ("destination.txt");
// Reading source file using read method
// and write to file byte by byte using write method
int temp;
while ((temp = sourceStream.read()) != -1)
targetStream.write((byte)temp);
}
finally
{
if (sourceStream != null){
sourceStream.close();
}
if (targetStream != null){
targetStream.close();
}
}
}
}
Output:
101000010001111111
After we execute the above program, it will create a file
called destination.txt in the same directory as the program file which
has the same content as of source.txt. If a file with the same name
already exists, an exception of FileAlreadyExistsException is thrown.
Character Stream in Java
In Java, character values are stored using Unicode conventions.
As we saw above, the Byte stream is used to perform input and
output operations of 8-bit bytes, but the Character stream is used
to perform input and output operations of 16-bit Unicode.
If we want to copy a text file containing characters from one
source to another destination using streams, character streams
would be advantageous as it deals with characters. Characters in
Java are 2 bytes or 16 bits in size.
In Java, the character streams too have a 3 phase mechanism similar
to that of Byte Streams as explained above.
Java provides many character stream classes, but the most common
ones are- FileReader- It is used to read two bytes at a time from the
source. The following is the constructor to create an instance of
the FileReader class.
FileReader in = new FileReader("path_to_file");
FileWriter- It is used to write two bytes at a time to the destination.
The following is the constructor to create an instance of
the FileWriter class.
FileWriter in = new FileWriter("path_to_file");
Stream class Description
BufferedReader Handles buffered input stream.
BufferedWriter Handles buffered output stream.
FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
OutputStreamReader Output stream that translate character to
byte.
PrintWriter Output Stream that
contain print() and println() method.
Reader Abstract class that define character stream
input
Writer Abstract class that define character stream
output
Example of Character Stream
This example deals with the usage of Character Stream to copy the
contents of one file to another. In the example, we will create two
objects of the FileReader and the FileWriter classes. The source and
the destination files names are given as parameters to
the FileReader and the FileWriter classes respectively. Then the
content of the source file will be copied to the destination file.
import java.io.*;
public class CharacterStreamExample {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
// Reading source file using read method
// and write to file using write method
try {
in = new FileReader("source.txt");
out = new FileWriter("destination.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Explanation - Let us assume that we have already created a file
named source.txt which has the following content-
Hi, we are learning about character stream.
After we execute the above program, it will create a file
called destination.txt which has the same content as of source.txt. If a
file with the same name already exists, an exception
of FileAlreadyExistsException is thrown.
Difference Between Byte Stream and Character Stream
Byte Stream Character Stream
Byte stream is used to perform
Character stream is used to perform input
input and output operations of 8-
and output operations of 16-bit Unicode.
bit bytes.
It processes data byte by byte. It processes data character by character.
Common classes for Byte stream
Common classes for Character streams are
are FileInputStream and
FileReader and FileWriter.
FileOutputStream.
Example- Byte streams are used Example- Character streams are used to
to read or write binary data. read/write characters.
Reading Console Input
We use the object of BufferedReader class to take inputs from the
keyboard.
Reading Characters
read() method is used with BufferedReader object to read characters.
As this function returns integer type value has we need to use
typecasting to convert it into char type.
Int read()throwsIOException
Below is a simple example explaining character input.
classCharRead
publicstaticvoidmain(Stringargs[])
{
BufferedReaderbr=newBufferedreader(newInputstreamReader(Syste
m.in));
char c =(char)br.read();//Reading character
Reading Strings in Java
To read string we have to use readLine() function with
BufferedReader class's object.
String readLine()throwsIOException
Program to take String input from Keyboard in Java
Import java.io.*;
classMyInput
publicstaticvoidmain(String[]args)
String text;
InputStreamReaderisr=newInputStreamReader(System.in);
BufferedReaderbr=newBufferedReader(isr);
text=br.readLine();//Reading String
System.out.println(text);
Program to read from a file using BufferedReader class
importjava.Io*;
classReadTest
publicstaticvoidmain(String[]args)
try
Filefl=newFile("d:/myfile.txt");
BufferedReaderbr=newBufferedReader(newFileReader(fl));
Stringstr;
while((str=br.readLine())!=null)
System.out.println(str);
}
br.close();
fl.close();
catch(IOException e){
e.printStackTrace();
Program to write to a File using FileWriter class
importjava.Io*;
classWriteTest
publicstaticvoidmain(String[]args)
try
Filefl=newFile("d:/myfile.txt");
Stringstr="Write this string to my file";
FileWriterfw=newFileWriter(fl);
fw.write(str);
fw.close();
fl.close();
catch(IOException e)
{e.printStackTrace();}
Java Serialization and Deserialization
Serialization is a process of converting an object into a sequence of
bytes which can be persisted to a disk or database or can be sent
through streams. The reverse process of creating object from
sequence of bytes is called deserialization.
A class must implement Serializable interface present
in java.io package in order to serialize its object
successfully. Serializable is a marker interface that adds serializable
behaviour to the class implementing it.
Java provides Serializable API encapsulated under java.io package
for serializing and deserializing objects which include,
java.io.serializable
ObjectInputStream
ObjectOutputStream
Java Marker interface
Marker Interface is a special interface in Java without any field and
method. Marker interface is used to inform compiler that the class
implementing it has some special behaviour or meaning. Some
example of Marker interface are,
java.io.serializable
java.lang.Cloneable
java.rmi.Remote
java.util.RandomAccess
To implement serialization and deserialization, Java provides two
classes ObjectOutputStream and ObjectInputStream.
ObjectOutputStream class
It is used to write object states to the file. An object that implements
java.io.Serializable interface can be written to streams. It provides
various methods to perform serialization.
ObjectInputStream class
An ObjectInputStreamde serializes objects and primitive data written
using an ObjectOutputStream.
writeObject() and readObject() Methods
The writeObject() method of ObjectOutputStream class serializes an
object and send it to the output stream.
Public final void writeObject(object x)throwsIOException
The readObject() method of ObjectInputStream class references
object out of stream and deserialize it.
Publicfinal
ObjectreadObject()throwsIOException,ClassNotFoundException
while serializing if you do not want any field to be part of object state
then declare it either static or transient based on your need and it
will not be included during java serialization process.
Example: Serializing an Object in Java
In this example, we have a class that implements Serializable
interface to make its object serialized.
importjava.io.*;
classStudentinfoimplementsSerializable
String name;
int rid;
static String contact;
Studentinfo(String n,int r,String c)
this.name = n;
this.rid= r;
this.contact= c;
classDemo
publicstaticvoidmain(String[]args)
try
Studentinfosi=newStudentinfo("Abhi",104,"110044");
FileOutputStreamfos=newFileOutputStream("student.txt");
ObjectOutputStreamoos=newObjectOutputStream(fos);
oos.writeObject(si);
oos.flush();
oos.close();
catch(Exception e)
System.out.println(e);
Object of Studentinfo class is serialized using writeObject() method
and written to student.txt file.
Example : Deserialization of Object in Java
To deserialize the object, we are using ObjectInputStream class that
will read the object from the specified file. See the below example.
importjava.io.*;
classStudentinfoimplementsSerializable
String name;
int rid;
staticString contact;
Studentinfo(String n,int r,String c)
this.name = n;
this.rid= r;
this.contact= c;
classDemo
publicstaticvoidmain(String[]args)
Studentinfosi=null;
try
FileInputStreamfis=newFileInputStream("/filepath/student.txt");
ObjectInputStreamois=newObjectInputStream(fis);
si=(Studentinfo)ois.readObject();
catch(Exception e)
e.printStackTrace();}
System.out.println(si.name);
System.out.println(si.rid);
System.out.println(si.contact);
Abhi
104
null
Contact field is null because,it was marked as static and as we have
discussed earlier static fields does not get serialized.
NOTE: Static members are never serialized because they are
connected to class not object of class.
transient Keyword
While serializing an object, if we don't want certain data member of
the object to be serialized we can mention it transient. transient
keyword will prevent that data member from being serialized.
Reading data from keyboard
There are many ways to read data from the keyboard. For example:
o InputStreamReader
o Console
o Scanner
o DataInputStream etc.
InputStreamReader class
InputStreamReader class can be used to read data from keyboard.It
performs two tasks:
o connects to input stream of keyboard
o converts the byte-oriented stream into character-oriented stream
BufferedReader class
BufferedReader class can be used to read data line by line by
readLine() method.
Example of reading data from keyboard by InputStreamReader and
BufferdReader class
In this example, we are connecting the BufferedReader stream with
the InputStreamReader stream for reading the line by line data from
the keyboard.
import java.io.*;
class G5{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}
Output:Enter your name
Amit
Welcome Amit
Another Example of reading data from keyboard by
InputStreamReader and BufferdReader class until the user writes stop
In this example, we are reading and printing the data until the user
prints stop.
import java.io.*;
class G5{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String name="";
while(!name.equals("stop")){
System.out.println("Enter data: ");
name=br.readLine();
System.out.println("data is: "+name);
}
br.close();
r.close();
}
}
Output:Enter data: Amit
data is: Amit
Enter data: 10
data is: 10
Enter data: stop
data is: stop
Java Console Class
The Java Console class is be used to get input from console. It
provides methods to read texts and passwords.
If you read password using Console class, it will not be displayed to
the user.
The java.io.Console class is attached with system console internally.
The Console class is introduced since 1.5.
Let's see a simple example to read text from console.
String text=System.console().readLine();
System.out.println("Text is: "+text);
Java Console class methods
Method Description
Reader reader() It is used to retrieve the reader object
associated with the console
String readLine() It is used to read a single line of text from the
console.
String readLine(String It provides a formatted prompt then reads the
fmt, Object... args) single line of text from the console.
char[] readPassword() It is used to read password that is not being
displayed on the console.
char[] It provides a formatted prompt then reads the
readPassword(String fmt, password that is not being displayed on the
Object... args) console.
Console format(String It is used to write a formatted string
fmt, Object... args) to the console output stream.
Console printf(String It is used to write a string to the console output
format, Object... args) stream.
PrintWriter writer() It is used to retrieve the PrintWriter
object associated with the console.
void flush() It is used to flushes the console.
Java Console Example to read password
import java.io.Console;
class ReadPasswordTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter password: ");
char[] ch=c.readPassword();
String pass=String.valueOf(ch);//converting char array into string
System.out.println("Password is: "+pass);
}
}
Output
Enter password:
Password is: 123
Java Scanner
Scanner class in Java is found in the java.util package. Java provides
various ways to read input from the keyboard, the java.util.Scanner
class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter
which is whitespace by default. It provides many methods to read and
parse various primitive values.
The Java Scanner class is widely used to parse text for strings and
primitive types using a regular expression. It is the simplest way to
get input in Java. By the help of Scanner in Java, we can get input
from the user in primitive types such as int, long, double, byte, float,
short, etc.
The Java Scanner class extends Object class and implements Iterator
and Closeable interfaces.
The Java Scanner class provides nextXXX() methods to return the
type of value such as nextInt(), nextByte(), nextShort(), next(),
nextLine(), nextDouble(), nextFloat(), nextBoolean(), etc. To get a
single character from the scanner, you can call next().charAt(0)
method which returns a single character.
Java Scanner Class Declaration
public final class Scanner extends Object implements Iterator<Strin
g>
1. To get the instance of Java Scanner which reads input from the
user, we need to pass the input stream (System.in) in the
constructor of Scanner class. For Example:
Scanner in = new Scanner(System.in);
2. To get the instance of Java Scanner which parses the strings, we
need to pass the strings in the constructor of Scanner class. For
Example:
Scanner in = new Scanner("Hello Javatpoint");
Java Scanner Class Methods
The following are the list of Scanner methods:
S Modifier & Method Description
N Type
1) void close() It is used to close this scanner.
2) pattern delimiter() It is used to get the Pattern
which the Scanner class is
currently using to match
delimiters.
3) Stream<MatchRe findAll() It is used to find a stream of
sult> match results that match the
provided pattern string.
4) String findInLine() It is used to find the next
occurrence of a pattern
constructed from the specified
string, ignoring delimiters.
5) string findWithinHorizo It is used to find the next
n() occurrence of a pattern
constructed from the specified
string, ignoring delimiters.
6) boolean hasNext() It returns true if this scanner
has another token in its input.
7) boolean hasNextBigDeci It is used to check if the next
mal() token in this scanner's input
can be interpreted as a
BigDecimal using the
nextBigDecimal() method or
not.
8) boolean hasNextBigInteg It is used to check if the next
er() token in this scanner's input
can be interpreted as a
BigDecimal using the
nextBigDecimal() method or
not.
9) boolean hasNextBoolean( It is used to check if the next
) token in this scanner's input
can be interpreted as a
Boolean using the
nextBoolean() method or not.
10) boolean hasNextByte() It is used to check if the next
token in this scanner's input
can be interpreted as a Byte
using the nextBigDecimal()
method or not.
11) boolean hasNextDouble() It is used to check if the next
token in this scanner's input
can be interpreted as a
BigDecimal using the
nextByte() method or not.
12) boolean hasNextFloat() It is used to check if the next
token in this scanner's input
can be interpreted as a Float
using the nextFloat() method
or not.
13) boolean hasNextInt() It is used to check if the next
token in this scanner's input
can be interpreted as an int
using the nextInt() method or
not.
14) boolean hasNextLine() It is used to check if there is
another line in the input of this
scanner or not.
15) boolean hasNextLong() It is used to check if the next
token in this scanner's input
can be interpreted as a Long
using the nextLong() method
or not.
16) boolean hasNextShort() It is used to check if the next
token in this scanner's input
can be interpreted as a Short
using the nextShort() method
or not.
17) IOException ioException() It is used to get the
IOException last thrown by
this Scanner's readable.
18) Locale locale() It is used to get a Locale of the
Scanner class.
19) MatchResult match() It is used to get the match
result of the last scanning
operation performed by this
scanner.
20) String next() It is used to get the next
complete token from the
scanner which is in use.
21) BigDecimal nextBigDecimal( It scans the next token of the
) input as a BigDecimal.
22) BigInteger nextBigInteger() It scans the next token of the
input as a BigInteger.
23) boolean nextBoolean() It scans the next token of the
input into a boolean value and
returns that value.
24) byte nextByte() It scans the next token of the
input as a byte.
25) double nextDouble() It scans the next token of the
input as a double.
26) float nextFloat() It scans the next token of the
input as a float.
27) int nextInt() It scans the next token of the
input as an Int.
28) String nextLine() It is used to get the input string
that was skipped of the
Scanner object.
29) long nextLong() It scans the next token of the
input as a long.
30) short nextShort() It scans the next token of the
input as a short.
31) int radix() It is used to get the default
radix of the Scanner use.
32) void remove() It is used when remove
operation is not supported by
this implementation of Iterator.
33) Scanner reset() It is used to reset the Scanner
which is in use.
34) Scanner skip() It skips input that matches the
specified pattern, ignoring
delimiters
35) Stream<String> tokens() It is used to get a stream of
delimiter-separated tokens
from the Scanner object which
is in use.
36) String toString() It is used to get the string
representation of Scanner
using.
37) Scanner useDelimiter() It is used to set the delimiting
pattern of the Scanner which is
in use to the specified pattern.
38) Scanner useLocale() It is used to sets this scanner's
locale object to the specified
locale.
39) Scanner useRadix() It is used to set the default
radix of the Scanner which is
in use to the specified radix.
Example 1
Let's see a simple example of Java Scanner where we are getting a
single input from the user. Here, we are asking for a string through
in.nextLine() method.
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}
Output:
Enter your name: sonoojaiswal
Name is: sonoojaiswal
Example 2
import java.util.*;
public class ScannerClassExample1 {
public static void main(String args[]){
String s = "Hello, This is JavaTpoint.";
//Create scanner Object and pass string in it
Scanner scan = new Scanner(s);
//Check if the scanner has a token
System.out.println("Boolean Result: " + scan.hasNext());
//Print the string
System.out.println("String: " +scan.nextLine());
scan.close();
System.out.println("--------Enter Your Details-------- ");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
in.close();
}
}
Output:
Boolean Result: true
String: Hello, This is JavaTpoint.
-------Enter Your Details---------
Enter your name: Abhishek
Name: Abhishek
Enter your age: 23
Age: 23
Enter your salary: 25000
Salary: 25000.0
Java.io.File Class in Java
The File class is Java’s representation of a file or directory
pathname. Because file and directory names have different
formats on different platforms, a simple string is not adequate
to name them.
The File class contains several methods for working with the
pathname, deleting and renaming files, creating new
directories, listing the contents of a directory, and determining
several common attributes of files and directories.
It is an abstract representation of files and directory pathnames.
A pathname, whether abstract or in string form can be either
absolute or relative. The parent of an abstract pathname may
be obtained by invoking the getParent() method of this class.
First of all, we should create the File class object by passing
the filename or directory name to it. A file system may
implement restrictions to certain operations on the actual
file-system object, such as reading, writing, and executing.
These restrictions are collectively known as access
permissions.
Instances of the File class are immutable; that is, once
created, the abstract pathname represented by a File object
will never change.
How to create a File Object?
A File object is created by passing in a string that represents
the name of a file, a String, or another File object. For
example,
File a = new File("/usr/local/bin/geeks");
This defines an abstract file name for the geeks file in the
directory /usr/local/bin. This is an absolute abstract file name.
Constructors of File Class
File(File parent, String child): Creates a new File instance
from a parent abstract pathname and a child pathname string.
File(String pathname): Creates a new File instance by
converting the given pathname string into an abstract
pathname.
File(String parent, String child): Creates a new File
instance from a parent pathname string and a child pathname
string.
File(URI uri): Creates a new File instance by converting the
given file: URI into an abstract pathname.
Methods of File Class
S. Return
No. Method Description Type
Tests whether the application
1. canExecute() can execute the file denoted by boolean
S. Return
No. Method Description Type
this abstract pathname.
Tests whether the application
can read the file denoted by this
2. canRead() abstract pathname. boolean
Tests whether the application
can modify the file denoted by
3. canWrite() this abstract pathname. boolean
compareTo(File Compares two abstract
4. pathname) pathnames lexicographically. int
Atomically creates a new,
empty file named by this
5. createNewFile() abstract pathname. boolean
createTempFile( Creates an empty file in the
String prefix, default temporary-file
6. String suffix) directory. File
Deletes the file or directory
denoted by this abstract
7. delete() pathname. boolean
equals(Object Tests this abstract pathname for
8. obj) equality with the given object. boolean
Tests whether the file or
directory denoted by this
9. exists() abstract pathname exists. boolean
S. Return
No. Method Description Type
Returns the absolute pathname
getAbsolutePath string of this abstract
10. () pathname. String
Returns an array of strings
naming the files and directories
11. list() in the directory. String[]
Returns the number of
unallocated bytes in the
12. getFreeSpace() partition. long
Returns the name of the file or
directory denoted by this
13. getName() abstract pathname. String
Returns the pathname string of
14. getParent() this abstract pathname’s parent. String
Returns the abstract pathname
of this abstract pathname’s
15. getParentFile() parent. File
Converts this abstract
pathname into a pathname
16. getPath() string. String
Marks the file or directory
named so that only read
17. setReadOnly() operations are allowed. boolean
18. isDirectory() Tests whether the file denoted boolean
S. Return
No. Method Description Type
by this pathname is a directory.
Tests whether the file denoted
by this abstract pathname is a
19. isFile() normal file. boolean
Tests whether the file named
by this abstract pathname is a
20. isHidden() hidden file. boolean
Returns the length of the file
denoted by this abstract
21. length() pathname. long
Returns an array of abstract
pathnames denoting the files in
22. listFiles() the directory. File[]
Creates the directory named by
23. mkdir() this abstract pathname. boolean
renameTo(File Renames the file denoted by
24. dest) this abstract pathname. boolean
setExecutable(bo A convenience method to set
olean the owner’s execute
25. executable) permission. boolean
setReadable(boo A convenience method to set
26. lean readable) the owner’s read permission. boolean
27. setReadable(boo Sets the owner’s or boolean
S. Return
No. Method Description Type
lean readable, everybody’s read permission.
boolean
ownerOnly)
setWritable(bool A convenience method to set
28. ean writable) the owner’s write permission. boolean
Returns the pathname string of
29. toString() this abstract pathname. String
Constructs a file URI that
represents this abstract
30. toURI() pathname. URI
Example1: Program to check if a file or directory physically exists
or not.
// In this Java program, we accepts a file or directory name from
// command line arguments. Then the program will check if
// that file or directory physically exist or not and
// it displays the property of that file or directory.
import java.io.File;
// Displaying file property
class fileProperty {
public static void main(String[] args)
{
// accept file name or directory name through
// command line args
String fname = args[0];
// pass the filename or directory name to File
// object
File f = new File(fname);
// apply File class methods on File object
System.out.println("File name :" + f.getName());
System.out.println("Path: " + f.getPath());
System.out.println("Absolute path:"
+ f.getAbsolutePath());
System.out.println("Parent:" + f.getParent());
System.out.println("Exists :" + f.exists());
if (f.exists()) {
System.out.println("Is writable:"
+ f.canWrite());
System.out.println("Is readable" + f.canRead());
System.out.println("Is a directory:"
+ f.isDirectory());
System.out.println("File Size in bytes "
+ f.length());
}
}
}
Output:
File name :file.txt
Path: file.txt
Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\file.txt
Parent:null
Exists :true
Is writable:true
Is readabletrue
Is a directory:false
File Size in bytes 20
Example 2: Program to display all the contents of a directory
Here we will accept a directory name from the keyboard and then
display all the contents of the directory. For this purpose, list()
method can be used as:
String arr[]=f.list();
In the preceding statement, the list() method causes all the directory
entries copied into the array arr[]. Then pass these array elements
arr[i] to the File object and test them to know if they represent a file
or directory.
// Java Program to display all
// the contents of a directory
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
// Displaying the contents of a directory
class Contents {
public static void main(String[] args)
throws IOException
{
// enter the path and dirname from keyboard
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter dirpath:");
String dirpath = br.readLine();
System.out.println("Enter the dirname");
String dname = br.readLine();
// create File object with dirpath and dname
File f = new File(dirpath, dname);
// if directory exists,then
if (f.exists()) {
// get the contents into arr[]
// now arr[i] represent either a File or
// Directory
String arr[] = f.list();
// find no. of entries in the directory
int n = arr.length;
// displaying the entries
for (int i = 0; i < n; i++) {
System.out.println(arr[i]);
// create File object with the entry and
// test if it is a file or directory
File f1 = new File(arr[i]);
if (f1.isFile())
System.out.println(": is a file");
if (f1.isDirectory())
System.out.println(": is a directory");
}
System.out.println(
"No of entries in this directory " + n);
}
else
System.out.println("Directory not found");
}
}
Output:
Enter dirpath:
C:\Users\akki\IdeaProjects\
Enter the dirname
codewriting
.idea
: is a directory
an1.txt
: is a file
codewriting.iml
: is a file
file.txt
: is a file
out
: is a directory
src
: is a directory
text
: is a file
No of entries in this directory 7