0% found this document useful (0 votes)
35 views77 pages

Exception

Dr. Sivanthi Aditanar College of Engineering organized a short-term training program on Object-Oriented Programming using Java from June 29 to July 4, 2020, focusing on exception handling and input/output basics. The document outlines the importance of exception handling, types of exceptions, and provides examples of Java's try-catch mechanism. It also discusses the hierarchy of exception classes and the differences between checked and unchecked exceptions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views77 pages

Exception

Dr. Sivanthi Aditanar College of Engineering organized a short-term training program on Object-Oriented Programming using Java from June 29 to July 4, 2020, focusing on exception handling and input/output basics. The document outlines the importance of exception handling, types of exceptions, and provides examples of Java's try-catch mechanism. It also discusses the hierarchy of exception classes and the differences between checked and unchecked exceptions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 77

Dr.

Sivanthi Aditanar College of


Engineering
Short Termon
Programme Training
Object
Oriented Programming
Using Java
From 29.6.2020 to
4.7.2020
Organized
Department of by
Computer
Science and
In Association Engineering
with Computer
1
Society of India Mar 10, 2025
Exception Handling
and
Input/Output Basics in Java
Mrs. S.V. Anandhi
Assistant Professor
CSE Department
Dr.Sivanthi Aditanar College of Engineering
2
Tiruchendur Mar 10, 2025
Agenda
• Exceptions
• Why Exception handling is important?
• What is Exception Handling in Java?
• Advantage of Exception Handling
• Hierarchy of Java Exception classes
• Types of Java Exceptions
• Keywords used in Exception handling
• Java Exception propagation
• Built-in Exceptions
• Creating Own Exceptions or User-defined Exceptions
• Input/Output Basics
Mar 10, 2025
3
EXCEPTIONS

• An exception is a problem that arises during


the execution of a program. When
an Exception occurs the normal flow of the
program is disrupted and the program
terminates abnormally. An exception can occur
for many different reasons.
• A user has entered an invalid data.
• A file that needs to be opened cannot be
found.
• A network connection has been lost in the
middle of communications or the JVM has run
out of memory
4 Mar 10, 2025
Difference between error and
exception
Errors mostly occur at runtime that's they
belong to an unchecked
type. Exceptions are the problems which
can occur at runtime and compile time. It
mainly occurs in the code written by the
developers

5 Mar 10, 2025


Why Exception handling is
important?
Exception handling is
important because it helps maintain the
normal, desired flow of the program even
when unexpected events occur.
If exceptions are not handled, programs
may crash or requests may fail.

6 Mar 10, 2025


What is Exception Handling in
Java?
The Exception Handling in Java is one of
the powerful mechanism to handle the
runtime errors such as
ClassNotFoundException, IOException,
SQLException , etc. so that normal flow of
the application can be maintained.

7 Mar 10, 2025


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:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
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.
8 Mar 10, 2025
Key differences in Exception
Handling in C++ vs Java

9 Mar 10, 2025


Hierarchy of Java Exception classes

 The java.lang.Throwable class is the root class of


Java Exception hierarchy which is inherited by two
subclasses: Exception and Error. A hierarchy of
Java Exception classes are given below:

10 Mar 10, 2025


11 Mar 10, 2025
12 Mar 10, 2025
Types of Java Exceptions
There are mainly two types of exceptions: checked and
unchecked.
1)Checked Exception
Checked exceptions are checked at compile-time.
The classes that extend Throwable class except RuntimeException and
Error are known as checked exceptions
e.g.IOException, SQLException etc.
2)Unchecked Exception
Unchecked exceptions are not checked at compile-time .
They are checked at runtime.
The classes that extend RuntimeException are known as unchecked
exceptions
e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
3)Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError.
13 Mar 10, 2025
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked
exceptions may occur. They are as follows:
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an
ArithmeticException.
int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing
any operation on the variable throws a
NullPointerException.
String s=null;
System.out.println(s.length());//
NullPointerException
14 Mar 10, 2025
3) A scenario where NumberFormatException occurs
The wrong formatting of any value may occur
NumberFormatException. Suppose I have a string
variable that has characters, converting this variable into
digit will occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException
occurs
If you are inserting any value in the wrong index, it would
result in ArrayIndexOutOfBoundsException as shown
below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
15 Mar 10, 2025
Output:
Exception in thread main
java.lang.ArithmeticException:/
by zero rest of the code...
In the above example, 100/0
raises an ArithmeticException
which is handled by a try-catch
block.

16 Mar 10, 2025


Five keywords used in Exception handling:
try
catch
finally
throw
throws

17 Mar 10, 2025


18 Mar 10, 2025
Java try-catch block

Java try block


Java try block is used to enclose the code
that might throw an exception. It must be
used within the method.
If an exception occurs at the particular
statement of try block, the rest of the block
code will not execute. So, it is
recommended not to keeping the code in
try block that will not throw an exception.
Java try block must be followed by either
catch or finally block.
19 Mar 10, 2025
Syntax of try with catch block
try
{
...
}
catch (Exception_class_Name reference)
{

}
Syntax of try with finally block
try
{
...
}
finally
{

}
20 Mar 10, 2025
Java catch block

Java catch block is used to handle the


Exception by declaring the type of
exception within the parameter. The
declared exception must be the parent
class exception ( i.e., Exception) or the
generated exception type. However, the
good approach is to declare the generated
type of exception.
The catch block must be used after the try
block only. You can use multiple catch block
with a single try block.
21 Mar 10, 2025
Problem without exception handling

Let's try to understand the problem if we don't use a try-catch block.


Example 1
public class TryCatchExample1 {

public static void main(String[] args) {

int data=50/0; //may throw exception

System.out.println("rest of the code");

}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero

As displayed in the above example, the rest of the code is not executed (in such
case, the rest of the code statement is not printed).There can be 100 lines of
code after exception. So all the code after exception will not be executed.

22 Mar 10, 2025


Problem with exception handling
Example
class Simple
{
public static void main(String args[])
{
try
{
int x = 55 / 0 ;
}
catch( ArithmeticException e )
{
System.out.println(e);
}
System.out.println("rest of the code...");
} }

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code... Mar 10, 2025
23
In this example, we also kept the code in a try block that will not throw an exception.
public class TryCatchExample3 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
System.out.println("rest of the code");
}
// handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}

}
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the rest of the block code will
not execute.

24 Mar 10, 2025


Here, we handle the exception using the parent class exception.
public class TryCatchExample4 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
// handling the exception by using Exception class
catch(Exception e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

}
Output:
java.lang.ArithmeticException: / by zero rest of the code
25 Mar 10, 2025
Let's see an example to print a custom message on exception.
public class TryCatchExample5 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
System.out.println("Can't divided by zero");
}
}

}
Output:
Can't divided by zero

26 Mar 10, 2025


Let's see an example to resolve the exception in a catch block.
public class TryCatchExample6 {

public static void main(String[] args) {


int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(i/(j+2));
}
}
}
Output:
25
27 Mar 10, 2025
In this example, along with try block, we also enclose exception code in a catch block.
public class TryCatchExample7 {

public static void main(String[] args) {

try
{
int data1=50/0; //may throw exception

}
// handling the exception
catch(Exception e)
{
// generating the exception in catch block
int data2=50/0; //may throw exception

}
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Here, we can see that the catch block didn't contain the exception code. So, enclose exception code within a try block and use catch
block only to handle the exceptions.

28 Mar 10, 2025


In this example, we handle the generated exception (Arithmetic Exception) with a
different type of exception class (ArrayIndexOutOfBoundsException).
public class TryCatchExample8 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception

}
// try to handle the ArithmeticException using ArrayIndexOutOfBoundsExceptio
n
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero

29 Mar 10, 2025


Let's see an example to handle another unchecked exception.
public class TryCatchExample9 {

public static void main(String[] args) {


try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

}
Output:
java.lang.ArrayIndexOutOfBoundsException: 10 rest of the code

30 Mar 10, 2025


Internal working of java try
catch block
The JVM firstly checks whether the exception
is handled or not. If exception is not handled,
JVM provides a default exception handler that
performs the following tasks:
Prints out exception description.
Prints the stack trace (Hierarchy of methods
where the exception occurred).
Causes the program to terminate.
But if exception is handled by the application
programmer, normal flow of the application is
maintained i.e. rest of the code is executed
31 Mar 10, 2025
32 Mar 10, 2025
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.
All catch blocks must be ordered from most
specific to most general, i.e. catch for
ArithmeticException must come before catch for
Exception.

33 Mar 10, 2025


Let's see a simple example of java multi-catch block. In this example, try block contains two exceptions.
But at a time only one exception occurs and its corresponding catch block is invoked.
public class MultipleCatchBlock1 {

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");
}
}
Output:
Arithmetic Exception occurs rest of the code

34 Mar 10, 2025


public class MultipleCatchBlock2 {

public static void main(String[] args) {

try{
int a[]=new int[5];

System.out.println(a[10]);
}
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");
}
}
Output:
ArrayIndexOutOfBounds Exception occurs rest of the code

35 Mar 10, 2025


Let's see an example, to handle the exception without maintaining the
order of exceptions (i.e. from most specific to most general).
class MultipleCatchBlock5{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e)
{System.out.println("common task completed");}
catch(ArithmeticException e)
{System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");}
System.out.println("rest of the code...");
}
}
Output:
Compile-time error
36 Mar 10, 2025
Nested Try Block:
try block within a try block is known as nested try block.
Syntax
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
37 Mar 10, 2025
class MultipleCatchBlock1
{
public static void main(String args[])
{
try
{
try
{
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}

}
catch(Exception e){System.out.println("handeled");}

System.out.println("normal flow..");
}
}
Output:
going to divide
java.lang.ArithmeticException: / by zero
normal flow..

38 Mar 10, 2025


Java finally block
Java finally block is a block that is used to
execute important code such as closing
connection, stream etc.
Java finally block is always executed
whether exception is handled or not.
Java finally block follows try or catch block.

39 Mar 10, 2025


40 Mar 10, 2025
Why use java finally?
Finally block in java can be used to put
"cleanup" code such as closing a file,
closing connection etc.

41 Mar 10, 2025


Case 1
Let's see the java finally example where exception
doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always execut
ed");}
System.out.println("rest of the code...");
}
}
Output:5 finally block is always executed rest of the code...

42 Mar 10, 2025


Case 2
Let's see the java finally example where exception
occurs and not handled.
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always execut
ed");}
System.out.println("rest of the code...");
}
}
Output:finally block is always executed Exception in thread
main java.lang.ArithmeticException:/ by zero
43 Mar 10, 2025
Case 3
Let's see the java finally example where exception occurs and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed rest of the code...

 Rule: For each try block there can be zero or more catch blocks, but only
one finally block.
 Note: The finally block will not be executed if program exits(either by calling
System.exit() or by causing a fatal error that causes the process to abort)

44 Mar 10, 2025


Java throw exception
Java throw keyword
The Java throw keyword is used to explicitly
throw an exception.
We can throw either checked or uncheked
exception in java by throw keyword. The throw
keyword is mainly used to throw custom
exception. We will see custom exceptions later.
The syntax of java throw keyword is given
below.
throw exception;
Let's see the example of throw IOException.
throw new IOException("sorry device error);
45 Mar 10, 2025
java throw keyword example
In this example, we have created the validate method that takes integer
value as a parameter. If the age is less than 18, we are throwing the
ArithmeticException otherwise print a message welcome to vote.
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid

46 Mar 10, 2025


Java Exception propagation

An exception is first thrown from the top of


the stack and if it is not caught, it drops
down the call stack to the previous
method,If not caught there, the exception
again drops down to the previous method,
and so on until they are caught or until
they reach the very bottom of the call
stack.This is called exception propagation.

47 Mar 10, 2025


Rule: By default Unchecked Exceptions are
forwarded in calling chain (propagated).
Program of Exception Propagation
class TestExceptionPropagation1{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e)
{System.out.println("exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExcept
ionPropagation1();
obj.p();
System.out.println("normal flow...");
}
}
Output:exception handled normal flow...

48 Mar 10, 2025


Rule: By default, Checked Exceptions are not forwarded in calling chain (propagated).
Program which describes that checked exceptions are not propagated
class TestExceptionPropagation2{
void m(){
throw new java.io.IOException("device error");//checked exception
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handeled");}
}
public static void main(String args[]){
TestExceptionPropagation2 obj=new TestExceptionPropagation2();
obj.p();
System.out.println("normal flow");
}
}
Output:Compile Time Error

49 Mar 10, 2025


Java throws keyword
The Java throws keyword is used to declare an exception. It gives
an information to the programmer that there may occur an
exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions.
If there occurs any unchecked exception such as
NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
Syntax of java throws
return_type method_name() throws exception_class_name{
//method code
}
Which exception should be declared
Ans) checked exception only, because:
unchecked Exception: under your control so correct your code.
error: beyond your control e.g. you are unable to do anything if
there occurs VirtualMachineError or StackOverflowError.

50 Mar 10, 2025


Advantage of Java throws keyword
Now Checked Exception can be propagated
(forwarded in call stack).
It provides information to the caller of the
method about the exception.

51 Mar 10, 2025


Let's see the example of java throws clause which describes that checked exceptions can
be propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled normal flow...

52 Mar 10, 2025


Rule: If you are calling a method that
declares an exception, you must either
caught or declare the exception.
There are two cases:
Case1:You caught the exception i.e. handle the
exception using try/catch.
Case2:You declare the exception i.e. specifying
throws with the method.

53 Mar 10, 2025


Case1: You handle the exception
In case you handle the exception, the code will be executed fine whether
exception occurs during the program or not.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}

System.out.println("normal flow...");
}
}
Output:exception handled normal flow...
54 Mar 10, 2025
Case2: You declare the exception
A)In case you declare the exception, if exception does not occur, the code will be
executed fine.
B)In case you declare the exception if exception occures, an exception will be
thrown at runtime because throws does not handle the exception.
A)Program if exception does not occur
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();

System.out.println("normal flow...");
}
}
Output:device operation performed normal flow...

55 Mar 10, 2025


B)Program if exception occurs
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//
declare exception
M m=new M();
m.method();

System.out.println("normal flow...");
}
}
Output:Runtime Exception
56 Mar 10, 2025
57 Mar 10, 2025
Java throw example
void m(){
throw new ArithmeticException("sorry");
}

Java throws example


void m()throws ArithmeticException{
//method code
}

Java throw and throws example


void m()throws ArithmeticException{
throw new ArithmeticException("sorry");
}
58 Mar 10, 2025
Built-in Exceptions:
• Java defines several exception classes inside
the standard package java.lang.
• The most general of these exceptions are
subclasses of the standard type
RuntimeException. Since java.lang is implicitly
imported into all Java programs, most
exceptions derived from RuntimeException are
automatically available.

59 Mar 10, 2025


• Creating Own Exceptions or User-defined Exceptions
Creating our own exception that is known as custom exception or user-defined exception. Java custom exceptions are used to
customize the exception according to user need.
Example
class InvalidAgeException extends Exception
{
InvalidAgeException(String s)
{
super(s);
}
}
class TestCustomException1
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
try
{
validate(13);
}
catch(Exception m)
{
System.out.println("Exception occured: "+m);
60 } Mar 10, 2025
System.out.println("rest of the code...");
Input/Output Basics:
The java.io package contains nearly every
class you might ever need to perform input
and output (I/O) in Java. All these streams
represent an input source and an output
destination. The stream in the java.io package
supports many data such as primitives, object,
localized characters, etc.
Stream
A stream can be defined as a sequence of
data. There are two kinds of Streams −
• InPutStream − The InputStream is used to
read data from a source.
• OutPutStream − The OutputStream is used
61 Mar 10, 2025
for writing data to a destination
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io
package contains all the classes required for input and output operations.
We can perform file handling in Java by Java I/O API.

Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called
a stream because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are
attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream

Let's see the code to print output and an error message to the console.
System.out.println("simple message");
System.err.println("error message");

Let's see the code to get input from console.


int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character

62 Mar 10, 2025


63 Mar 10, 2025
64 Mar 10, 2025
65 Mar 10, 2025
66 Mar 10, 2025
67 Mar 10, 2025
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently
used classes are, FileInputStream and FileOutputStream.
Example
import java.io.*;
public class Bytstream
{
public static void main(String args[]) throws IOException
{
FileInputStream in = new FileInputStream("input.txt");
FileOutputStream out = new FileOutputStream("output.txt");
int c;
try
{
while ((c = in.read()) != -1)
{
out.write(c);
}}
finally
{
System.out.println("Byte stream code executed");
}
}}
Now let's have a file input.txt with the following content:
This is test for copy file.
As a next step, compile above program and execute it, which will result in creating output.txt file
with the same content as we have in input.txt. So let's put above code in CopyFile.java file and do
the following:
$ javac CopyFile.java
$ java CopyFile
68 Mar 10, 2025
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to perform input and output for 16-bit unicode.
Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter.
FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter
writes two bytes at a time.
Example
import java.io.*;
public class CopyFile
{
public static void main(String args[]) throws IOException
{
FileReader in = new FileReader("input.txt");
FileWriter out = new FileWriter("output.txt");
int c;
try
{
while ((c = in.read()) != -1)
{
out.write(c);
}}
finally
{
System.out.println("Character stream code executed");
}}}
Now let's have a file input.txt with the following content:
This is test for copy file.
As a next step, compile above program and execute it, which will result in creating output.txt file
with the same content as we have in input.txt. So let's put above code in CopyFile.java file and do
the following:
$ javac CopyFile.java
69 $ java CopyFile Mar 10, 2025
Standard Streams
All the programming languages provide support for
standard I/O where the user's program can take input
from a keyboard and then produce an output on the
computer screen. Java provides the following three
standard streams −
Standard Input − This is used to feed the data to user's
program and usually a keyboard is used as standard
input stream and represented as System.in.
Standard Output − This is used to output the data
produced by the user's program and usually a computer
screen is used for standard output stream and
represented as System.out.
Standard Error − This is used to output the error data
produced by the user's program and usually a computer
screen is used for standard error stream and
represented as System.err.
70 Mar 10, 2025
Following is a simple program which creates InputStreamReader to read standard input stream
until the user types a "q":.
Example
Following is a simple program which creates InputStreamReader to read standard input stream
until the user types a "q":
im port java.io.* ;
public class ReadConsole {
public static void m ain(String args[]) throws IOException
{
InputStream Reader cin = null;
try {
cin = new InputStream Reader(System .in);
System .out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System .out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
Let's keep above code in ReadConsole.java file and try to compile and execute it as below. This
program continues reading and outputting same character until we press 'q':
$ javac ReadConsole.java
$ java ReadConsole
Enter characters, 'q' to quit.
1
71 1 Mar 10, 2025
e
Reading Files
Reader is the abstract class for reading character
streams.
The following diagram show relationship of these
reader classes in the java.io package:

InputStreamReader is a bridge from byte streams


to character streams. It converts bytes into
characters using a specified charset.
FileReader is a convenient class for reading text files
using the default character encoding of the
operating system.
BufferedReader reads text from a character stream
and provides a convenient method for reading a line
of text readLine().
72 Mar 10, 2025
Example
import java.io.*;
public class Rfile
{
public static void main(String[] args) throws IOException
{
try
{
FileReader reader = new FileReader("output.txt");
int ch;
while ((ch = reader.read()) != -1)
{
System.out.print((char) ch);
}
reader.close();
}
finally
{
System.out.println("Reading file executed");
}}}
Output : Hi…. Reading file executed

73 Mar 10, 2025


Writing Files
Writer is the abstract class for writing character
streams
The following diagram show relationship of these
writer classes in the java.io package:
OutputStreamWriter is a bridge from byte
streams to character streams.
FileWriter is a convenient class for writing text
files using the default character encoding of the
operating system.
BufferedWriter writes text to a character stream
with efficiency and provides a convenient
method for writing a line separator: newLine().

74 Mar 10, 2025


Example
import java.io.*;
public class Wfile
{
public static void main(String[] args)throws IOException
{
try
{
FileWriter writer = new FileWriter("MyFile1.txt");
writer.write("Hello World");
writer.write("\n Good Bye!");
writer.close();
}
finally
{
System.out.println("File writing completed");
}}}
Output: File writing completed
75 Mar 10, 2025
THANK YOU!!!

76 Mar 10, 2025


QUERIES ??

77 Mar 10, 2025

You might also like