0% found this document useful (0 votes)
2 views

Lecture Slide - Week 7

The document provides an overview of exception handling in Java, explaining its importance in maintaining the normal flow of applications during runtime errors. It details various types of exceptions, including checked and unchecked exceptions, and outlines the keywords used in exception handling such as try, catch, finally, throw, and throws. Additionally, it discusses the internal workings of Java's exception handling mechanism and provides examples of common scenarios where exceptions may occur.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lecture Slide - Week 7

The document provides an overview of exception handling in Java, explaining its importance in maintaining the normal flow of applications during runtime errors. It details various types of exceptions, including checked and unchecked exceptions, and outlines the keywords used in exception handling such as try, catch, finally, throw, and throws. Additionally, it discusses the internal workings of Java's exception handling mechanism and provides examples of common scenarios where exceptions may occur.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 150

OBJECT ORIENTED

PROGRAMMING
USING JAVA
 Introduction
 Default Exceptional handler
 try

OUTLINE  catch
 finally
 throw
 throws
WHAT IS EXCEPTION??

 Dictionary Meaning: Exception is an abnormal condition.


 An unwanted / unexpected event that disturbs, normal flow of the program
(execution) is called exception.
 In java, exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
Example
1. Read data from remote file, locating at Bennett University (file not found
exception)
2. Online class exception- scenario, where during class your internet stop
working.
TYPES OF PROGRAM ERRORS

We distinguish between the following types of errors:


1.Syntax errors: errors due to the fact that the syntax of the language is not
respected.
2. Semantic errors: errors due to an improper use of program statements.
3.Logical errors: errors due to the fact that the specification is not respected.
From the point of view of when errors are detected, we distinguish:
4.Compile time errors: syntax errors and static semantic errors indicated by the
compiler.
5.Runtime errors: dynamic semantic errors, and logical errors, that cannot be
detected by the compiler(debugging).
WHAT IS THE PURPOSE OF EXCEPTIONAL HANDLING??
Example:
Opend db connetion
Request 3
Open connection Request 1
Read the data server
Sql exception Request 10
Request 2
Close connection

Problem: Because of exception we should not block or miss something.


Solution: Exceptional Handling
Example: Problem: Writing code on code zinger, suddenly power cut occur
then it may lead to loss of data.
Solution: Have power back up.
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.
 Exceptional handling does not mean repairing an exception.
 Here we have to provide alternative way to continue the rest of the program
normally is the concept of exceptional handling.

 Example: Our programming requirement is to read data from remote file


locating at Bennett university. At run time, if Bennett university file is not
available. If we want that our program should not terminated abnormally, then
we have to provide some local file to continue rest of the program normally.
This way of defining alternative is nothing but exception handling.
ADVANTAGE OF EXCEPTION HANDLING

 The core advantage of exception handling is to


maintain the normal flow of the application.  Let's take a scenario:

 Exception normally disrupts the normal flow of  statement 1;


the application that is why we use exception
 statement 2;
handling.
 statement 3; //exception occurs
 Suppose there is 6 statements in your program
and there occurs an exception at statement 3, rest  statement 4;
of the code will not be executed i.e. statement 4
to 6 will not run. If we perform exception  statement 5;
handling, rest of the statement will be executed.  statement 6;
That is why we use exception handling in java.
RUNTIME STACK MECHANISM
• Runtime Stack Mechanism as its name indicates is a Stack that have been created by JVM for each Thread at
the time of Thread creation, JVM store every methods calls performed by that Thread in the Stack.
• Each entry or method call called "activation record" / "stack frame".

Output :
Bennett University
DEFAULT EXCEPTIONAL HANDLING IN JAVA

Output
DEFAULT EXCEPTIONAL HANDLING IN JAVA (PROCESS)
If an exception raised, the method in which it’s raised is
responsible for the creation of Exceptions object by • If the main() method also doesn’t contain
including the following information: exception handling code the JVM terminates
• Name of the Exception that main() method and removes the
• Description of the Exception corresponding entry from the stack.
• Stack Trace • Just before terminating the program abnormally
• After creating Exception object the method JVM handovers the responsibility of exception
handover it to the JVM. handling to the Default Exception Handler which
• JVM checks for Exception Handling code in that is the component of JVM.
method. • Default Exception Handler just print exception
If the method doesn’t contain any Exception handling code information to the console in the following
then JVM terminates the method abnormally and removes format:
the corresponding entry from the stack.
• JVM identify the caller method and checks for Name of Exception: Description
Exception Handling code in that method. If the caller
doesn’t contain any exception handling code then JVM Stack Trace (Location of the Exception)
terminates that method abnormally and removes the
corresponding entry from the stack.
• This process will be continue until main() method.
EXAMPLE:
EXAMPLE:
PREDICT THE OUTPUT??
PREDICT THE OUTPUT??
NOTE:

 If at least one method terminates abnormally then termination of a program is


abnormal.
 If we are not satisfied with the default then we will go for customised
exceptional handling
HIERARCHY OF JAVA EXCEPTION CLASSES

• Object class is the parent class of all the classes in java


• In Java, all errors and exceptions are represented
with Throwable class.
• When an error occurs within a method, the method creates an
object (of any subtype of Throwable) and hands it off to the
runtime system.
• The object, called an exception object.
• Exception object contains information about the error,
including its type and the state of the program when the
error occurred.
• Creating an exception object and handing it to the runtime
system is called throwing an exception.
EXCEPTION VS ERROR
 Most of the time Exceptions are caused by programs and are recoverable.
 Most of the time errors are not caused by our program , and these are due to lack
of system resources. Errors are irrecoverable.

Error Example Exception Example


TYPES OF EXCEPTION

There are mainly two types of exceptions:


 checked and unchecked
 where error is considered as unchecked exception.

The sun microsystem says there are three types of exceptions:


 Checked Exception
 Unchecked Exception
 Error

 Note: All exception occur at runtime


1) CHECKED EXCEPTION
 The exception checked by the compiler for the smooth execution of the program during
runtime.
 The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions
 e.g.IOException, SQLException etc.
 Checked exceptions are checked at compile-time.
1) CHECKED EXCEPTION
 The exception checked by the compiler for the smooth execution of the program during
runtime.
 The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions
 e.g.IOException, SQLException etc.
 Checked exceptions are checked at compile-time.
Output:
Exception in thread "main"
java.lang.RuntimeException:Uncompilable source
code -
unreported exception
java.io.FileNotFoundException;must be caught or
declared to be
thrown
at Main.main(Main.java:5)
2) UNCHECKED EXCEPTION
 The classes that extend RuntimeException are known as unchecked exceptions.
 These include programming bugs, such as logic errors or improper use of an API. Runtime
exceptions are ignored at the time of compilation.
 e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
 Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
2) UNCHECKED EXCEPTION
 The classes that extend RuntimeException are known as unchecked exceptions.
 These include programming bugs, such as logic errors or improper use of an API. Runtime
exceptions are ignored at the time of compilation.
 e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
 Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
3) ERROR

 Errors are irrecoverable


 e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Checked Exception Unchecked Exception
Checked exceptions occur at compile time. Unchecked exceptions occur at runtime.

The compiler checks a checked exception. The compiler does not check these types of exceptions.

These types of exceptions can be handled at the time of These types of exceptions cannot be a catch or handle at the time
compilation. of compilation, because they get generated by the mistakes in the
program.

They are the sub-class of the exception class. They are runtime exceptions and hence are not a part of the
Exception class.

Here, the JVM needs the exception to catch and handle. Here, the JVM does not require the exception to catch and handle.

Examples of Checked exceptions: Examples of Unchecked Exceptions:


• No Such Element Exception
• File Not Found Exception
• Undeclared Throwable Exception
• No Such Field Exception
• Empty Stack Exception
• Interrupted Exception
• Arithmetic Exception
• No Such Method Exception
• Null Pointer Exception
• Class Not Found Exception
• Array Index Out of Bounds Exception
• Security Exception
COMMON SCENARIOS WHERE EXCEPTIONS MAY OCCUR

 There are given some scenarios where unchecked exceptions can occur. They
are as follows:
 1) Scenario where ArithmeticException occurs
 If we divide any number by zero, there occurs an ArithmeticException.
 int a=50/0;//ArithmeticException
COMMON SCENARIOS WHERE EXCEPTIONS MAY OCCUR

 2) Scenario where NullPointerException occurs

 If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
 String s=null;
 System.out.println(s.length());//NullPointerException
COMMON SCENARIOS WHERE EXCEPTIONS MAY OCCUR

 3) Scenario where NumberFormatException occurs

 The wrong formatting of any value, may occur NumberFormatException.


 Suppose I have a string variable that have characters, converting this variable into digit
will occur NumberFormatException.
 String s="abc";
 int i=Integer.parseInt(s);//NumberFormatException
COMMON SCENARIOS WHERE EXCEPTIONS MAY OCCUR

 4) Scenario where ArrayIndexOutOfBoundsException occurs

 if you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
JAVA EXCEPTION HANDLING KEYWORDS

 There are 5 keywords used in java exception handling.


 try
 catch
 finally
 throw
 throws
CUSTOMIZED EXCEPTIONAL HANDLING USING TRY AND CATCH
try block

 Java try block is used to enclose the code that might throw an exception. It must be
used within the method.

 Java try block must be followed by either catch or finally block.


SYNTAX OF JAVA TRY-CATCH

try{
//code that may throw exception
}catch(Exception_class_Name ref){}

Syntax of try-finally block

try{
//code that may throw exception
}finally{}
CATCH BLOCK

 Java catch block is used to handle the Exception.

 It must be used after the try block only.

 You can use multiple catch block with a single try.


PROBLEM WITHOUT EXCEPTION HANDLING
PROBLEM WITHOUT EXCEPTION HANDLING

output
PROBLEM USING TRY-CATCH
PROBLEM USING TRY-CATCH

Risky code

The code which may rise an exception is called risky code and
we have to define that code inside try block and corresponding
handling code we have to define inside catch block.

output
INTERNAL WORKING OF JAVA TRY-CATCH BLOCK
EXPLANATION

• 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.
CONTROL FLOW INTRY CATCH
Case 1: if there is no exception
CONTROL FLOW IN TRY CATCH
Case 1: if there is no exception
Order of execution
output

Termination:normal
CONTROL FLOW INTRY CATCH
Case 2: if there is an exception in statement 2 of try
CONTROL FLOW IN TRY CATCH
Case 2: if there is an exception in statement 2 of try

Order of
execution
output

Termination:normal

Note: Hence length of try block should be as less as possible and take only risky code inside try block
Or go for multiple try block
CONTROL FLOW INTRY CATCH
Case 3: if there is an exception in statement 2 and corresponding catch not matched
CONTROL FLOW IN TRY CATCH
Case 3: if there is an exception in statement 2 and corresponding catch not matched

Order of execution
output

Termination:Abnormal
CONTROL FLOW INTRY CATCH
Case 4: if there is an exception in try as well as in catch statement or outside try statement
CONTROL FLOW IN TRY CATCH
Case 4: if there is an exception in try as well as in catch statement or outside try statement

Order of execution
output

Termination:Abnormal
NOTE:

1.With in the try block if anywhere an exception occur then rest of the
try wont be executed even though we handled that exception hence with
in the try block we have to take only risky code and length of try
block should be as less as possible.
2.In addition other than try block there may be chance of rising an
exception inside catch and finally blocks.
3.If any statement which is not part of try block and an exception occur
then it is always abnormal termination.
METHODS TO PRINT EXCEPTION INFORMATION

printStackTrace()
toString() getMessage()
TRYWITH MULTIPLE CATCH BLOCKS

Case: 1 Case:2 Case:3


TRYWITH MULTIPLE CATCH BLOCKS

• The way of handling an exception is varied from exception to exception, hence


for every exception type it is highly recommended to take separate catch block
i.e. try with multiple catch block is always possible and recommended to use.
• At a time only one Exception is occurred and at a time only one catch block is
executed

Limitation
• Order of execution is very important when having multiple catch, because first
we will take child first and the parent exception, if we take parent exception
first and then child exception you will surely get a compilation error.
TRY WITH MULTIPLE CATCH BLOCKS
 If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch block

public class TestMultipleCatchBlock{


public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
catch(Exception e){System.out.println("common task completed");}

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


}
}
TRY WITH MULTIPLE CATCH BLOCKS
 If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch block

public class TestMultipleCatchBlock{


public static void main(String args[]){
try{
int a[]=new int[5];
a[4]=30/0;
}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
catch(Exception e){System.out.println("common task completed");}

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


} Output:
} task1 is completed
rest of the code
TRY WITH MULTIPLE CATCH BLOCKS
 If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch block

public class TestMultipleCatchBlock{


public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/1;
}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
catch(Exception e){System.out.println("common task completed");}

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


}
}
TRY WITH MULTIPLE CATCH BLOCKS
 If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch block

public class TestMultipleCatchBlock{


public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/1;
}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
catch(Exception e){System.out.println("common task completed");}

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


} task2 is completed
} Rest of the code
JAVA NESTED TRY BLOCK

 The try block within a try block is known as nested try block in java.

 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.
JAVA NESTED TRY BLOCK: EXAMPLE

output
JAVA FINALLY BLOCK
 Finally block is used to perform clean-up activities that we related to try block , means
what ever resources we open in the try block will be closed inside finally block.

 Java finally block is a block that is used to execute important code such as closing
connection, closing a file etc.

 Java finally block is always executed whether exception is handled or not.

 Java finally block follows try or catch block.


CASE 1: 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 executed");}
System.out.println("rest of the code...");
}
}
CASE 1: FINALLY EXAMPLE WHERE EXCEPTION DOESN'T OCCUR
class TestFinallyBlock{
public static void main(String args[]){
try{
Output:
int data=25/5; 5
System.out.println(data); finally block is always executed
rest of the code...
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
CASE 2: 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 executed");}
System.out.println("rest of the code...");
}
}
CASE 2: FINALLY EXAMPLE WHERE EXCEPTION OCCURS AND NOT
HANDLED.
class TestFinallyBlock1{
public static void main(String args[]){
try{
Output:
int data=25/0; finally block is always executed
Exception in thread main
System.out.println(data);
java.lang.ArithmeticException:/ by zero
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
CASE 3:FINALLY EXAMPLE WHERE EXCEPTION OCCURS AND HANDLED.

public class TestFinallyBlock2{  Output


public static void main(String args[]){  Exception in thread main
java.lang.ArithmeticException:/ by zero
try{  finally block is always executed
int data=25/0;  rest of the code...

System.out.println(data);
}  Note:
 For each try block there can be zero or more
catch(ArithmeticException e){System.out.println(e);} catch blocks,but only one finally block.
finally{System.out.println("finally block is always exe
cuted");}  The finally block will not be executed if program
exits(either by calling System.exit()
System.out.println("rest of the code...");  or by causing a fatal error that causes the process
} to abort).

}
THROW KEYWORD

 Some times we can create exception object explicitly and handover the object
manually for which we use throw keyword.

 The Java throw keyword is used to explicitly throw an exception.


 We can throw either checked or un-checked exception in java by throw keyword.
 Hence the main objective of throw keyword is to handover the object manually to
jvm.
 Note: throw keyword are used for custom/ user defined exception.
EXAMPLE
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
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.

Note: the next line after throw exception will give us unreachable statement because compiler is aware
about that statement that it is not going to execute.
JAVA EXCEPTION PROPAGATION: EXAMPLE
class TestExceptionPropagation1{
void m(){
public static void main(String args[]){
int data=50/0;
} TestExceptionPropagation1 obj=new
void n(){ TestExceptionPropagation1();
m(); obj.p();
} System.out.println("normal flow...");
}
void p(){
}
try{
n();
}catch(Exception e){System.out.println("exception h
andled");}
}
OUTPUT
 exception handled

 normal flow...
CHECKED EXCEPTION
class TestExceptionPropagation2{
void m(){
throw new java.io.IOException("de public static void main(String args[]){
vice error");//checked exception TestExceptionPropagation2 obj=new TestExce
} ptionPropagation2();
void n(){ obj.p();
m();
System.out.println("normal flow");
}
}
}
void p(){
try{
n();
}catch(Exception e){System.out.printl
n("exception handeled");}
}
throws KEYWORD

 The Java throws keyword is used to declare an exception.


 To delegate the responsibility of exceptional handling to the caller method, caller
method can be another method or jvm. Then caller method is responsible to handle
the 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.
 Note: It is generally used for checked exception.
 Throws keyword does not prevent us from abnormal termination
Syntax of java throws

return_type method_name() throws exception_class_name{


//method code
}
Which exception should be declared

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.
Example
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...");
} }
Example
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception }
void n()throws IOException{
m(); } OUTPUT
exception handled
void p(){ normal flow...
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...");
} }
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.
Case1:You handle the exception
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..."); }}
Case1:You handle the exception
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
} OUTPUT:
exception handled
public class Testthrows2{ normal flow...
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..."); }}
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 occurs, 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{ OUTPUT:
device operation performed
System.out.println("device operation performed"); normal flow...
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
} }
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...");
}
}
B)Program if exception occurs
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
} Output:
} Runtime Exception
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();

System.out.println("normal flow...");
}
}
Difference between throw and throws in Java
No. throw throws
1) Java throw keyword is used to explicitly throw an Java throws keyword is used to declare an
exception. exception.
2) Checked exception cannot be propagated using Checked exception can be propagated with throws.
throw only.
3) Throw is followed by an instance. Throws is followed by class.
4) Throw is used within the method. Throws is used with the method signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.
 Overview of Streams and File I/O
 Text-File I/O
 Using the File Class

OUTLINE  Basic Binary-File I/O


 Object I/O with Object Streams
 (optional) Graphics Supplement
Streams

Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a
source (keyboard, file, etc.)
it acts as a buffer between the data source and destination
Input stream: a stream that provides input to a program
System.in is an input stream
Output stream: a stream that accepts output from a program
System.out is an output stream
A stream connects a program to an I/O object
System.out connects a program to the screen
System.in connects a program to the keyboard
Binary Versus Text Files
All data and programs are ultimately just zeros and ones
each digit can have one of two values, hence binary
bit is one binary digit
byte is a group of eight bits
Text files: the bits represent printable characters
one byte per character for ASCII, the most common code
for example, Java source files are text files
so is any file created with a "text editor"
Binary files: the bits represent other types of encoded information, such as
executable instructions or numeric data
these files are easily read by the computer but not humans
they are not "printable" files
actually, you can print them, but they will be unintelligible
"printable" means "easily readable by humans when printed"
Java: Text Versus Binary Files
Text files are more readable by humans
Binary files are more efficient
computers read and write binary files more easily than text
Java binary files are portable
they can be used by Java on different machines
Reading and writing binary files is normally done by a program
text files are used only to communicate with humans
https://www.geeksforgeeks.org/compilation-execution-java-program/

Java Text Files Java Binary Files


• Source files • Executable files (created by
• Occasionally input files compiling source files)
• Occasionally output files • Usually input files
• Usually output files
Text Files vs. Binary Files
Number: 127 (decimal)
Text file
Three bytes: “1”, “2”, “7”
ASCII (decimal): 49, 50, 55
ASCII (octal): 61, 62, 67
ASCII (binary): 00110001, 00110010, 00110111
Binary file:
One byte (byte): 01111110
Two bytes (short): 00000000 01111110
Four bytes (int): 00000000 00000000 00000000 01111110
Text File I/O
Important classes for text file output (to the file)
PrintWriter
FileOutputStream [or FileWriter]
Important classes for text file input (from the file):
BufferedReader
FileReader
FileOutputStream and FileReader take file names as arguments.
PrintWriter and BufferedReader provide useful methods for easier
writing and reading.
Usually need a combination of two classes
To use these classes your program needs a line like the following:
import java.io.*;
Buffering
Not buffered: each byte is read/written from/to disk as soon as possible
“little” delay for each byte
A disk operation per byte---higher overhead
Buffered: reading/writing in “chunks”
Some delay for some bytes
Assume 16-byte buffers
Reading: access the first 4 bytes, need to wait for all 16 bytes are read
from disk to memory
Writing: save the first 4 bytes, need to wait for all 16 bytes before
writing from memory to disk
A disk operation per a buffer of bytes---lower overhead
Every File Has Two Names

1.the stream name used by Java


outputStream in the example
2.the name used by the operating system
out.txt in the example
Text File Output
To open a text file for output: connect a text file to a stream for writing
PrintWriter outputStream =
new PrintWriter(new FileOutputStream("out.txt"));

Similar to the long way:


FileOutputStream s = new FileOutputStream("out.txt");
PrintWriter outputStream = new PrintWriter(s);

Goal: create a PrintWriter object


which uses FileOutputStream to open a text file
FileOutputStream “connects” PrintWriter to a text file.
Output File Streams

PrintWriter FileOutputStream

Memory Disk

smileyOutStream smiley.txt

PrintWriter smileyOutStream = new PrintWriter( new FileOutputStream(“smiley.txt”) );


Methods for PrintWriter
Similar to methods for System.out.println

outputStream.println(count + " " + line);

print
format
flush: write buffered output to disk
close: close the PrintWriter stream (and file)
TextFileOutputDemo
Part 1 A try-block is a block:
outputStream would
public static void main(String[] args)
{ not be accessible to the
PrintWriter outputStream = null; rest of the method if it
try were declared inside the
Opening the file { try-block
outputStream =
new PrintWriter(new FileOutputStream("out.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file out.txt. “
+ e.getMessage());
System.exit(0); Creating a file can cause the
}
FileNotFound-Exception if
the new file cannot be made.
TextFileOutputDemo
Part 2 System.out.println("Enter three lines of text:");
String line = null;
int count;
for (count = 1; count <= 3; count++)
{
line = keyboard.nextLine();
outputStream.println(count + " " + line);
}
outputStream.close(); Writing to the file
System.out.println("... written to out.txt.");
}
Closing the file

The println method is used with two different


streams: outputStream and System.out
Gotcha: Overwriting a File
Opening an output file creates an empty file

Opening an output file creates a new file if it does not already exist

Opening an output file that already exists eliminates the old file and creates
a new, empty one
data in the original file is lost

To see how to check for existence of a file, see the section of the text that
discusses the File class (later slides).
Java Tip: Appending to a Text File
To add/append to a file instead of replacing it, use a different constructor for
FileOutputStream:
outputStream =
new PrintWriter(new FileOutputStream("out.txt",
true));

Second parameter: append to the end of the file if it exists?


Sample code for letting user tell whether to replace or append:

System.out.println("A for append or N for new file:");


char ans = keyboard.next().charAt(0);
boolean append = (ans == 'A' || ans == 'a'); true if user
outputStream = new PrintWriter( enters 'A'
new FileOutputStream("out.txt", append));
Closing a File
An output file should be closed when you are done writing to
it (and an input file should be closed when you are done
reading from it).

Use the close method of the class PrintWriter


(BufferedReader also has a close method).

For example, to close the file opened in the previous example:


outputStream.close();
If a program ends normally it will close any files that are open.
FAQ: Why Bother to Close a File?
If a program automatically closes files when it ends normally, why close
them with explicit calls to close?

Two reasons:
1. To make sure it is closed if a program ends abnormally (it could get
damaged if it is left open).

2. A file opened for writing must be closed before it can be opened for
reading.
Although Java does have a class that opens a file for both reading
and writing, it is not used in this text.
Text File Input
To open a text file for input: connect a text file to a stream for reading
Goal: a BufferedReader object,
which uses FileReader to open a text file
FileReader “connects” BufferedReader to the text file
For example:
BufferedReader smileyInStream =
new BufferedReader(new FileReader(“smiley.txt"));
Similarly, the long way:
FileReader s = new FileReader(“smiley.txt");
BufferedReader smileyInStream = new
BufferedReader(s);
Input File Streams

BufferedReader FileReader

Memory Disk

smileyInStream smiley.txt

BufferedReader smileyInStream = new BufferedReader( new FileReader(“smiley.txt”) );


Methods for BufferedReader

readLine: read a line into a String


no methods to read numbers directly, so read numbers as Strings and then convert them
(StringTokenizer later)
read: read a char at a time
close: close BufferedReader stream
Exception Handling with File I/O
Catching IOExceptions
IOException is a predefined class
File I/O might throw an IOException
catch the exception in a catch block that at least prints an error message and
ends the program
FileNotFoundException is derived from IOException
therefor any catch block that catches IOExceptions also catches
FileNotFoundExceptions
put the more specific one first (the derived one) so it catches specifically
file-not-found exceptions
then you will know that an I/O error is something other than file-not-found
public static void main(String[] args)
Example: {
String fileName = null; // outside try block, can be used in catch
Reading a File Name try
{ Scanner keyboard = new Scanner(System.in);
from the Keyboard System.out.println("Enter file name:");
fileName = keyboard.next();
BufferedReader inputStream =
reading a file name new BufferedReader(new FileReader(fileName));
from the keyboard String line = null;
line = inputStream.readLine();
System.out.println("The first line in " + filename + " is:");
using the file name System.out.println(line);
read from the // . . . code for reading second line not shown here . . .
keyboard inputStream.close();
} closing the file
catch(FileNotFoundException e)
reading data {
System.out.println("File " + filename + " not found.");
from the file }
catch(IOException e)
{
System.out.println("Error reading from file " + fileName);
}
}
Chapter 10 Java: an Introduction to Computer Science & Programming - Walter Savitch 104
Exception.getMessage()
try
{

}
catch (FileNotFoundException e)
{
System.out.println(filename + “ not found”);
System.out.println(“Exception: “ +
e.getMessage());
System.exit(-1);
}
Reading Words in a String:
Using StringTokenizer Class
There are BufferedReader methods to read a line and a character, but not just a single
word

StringTokenizer can be used to parse a line into words


import java.util.*
some of its useful methods are shown in the text
e.g. test if there are more tokens
you can specify delimiters (the character or characters that separate words)
the default delimiters are "white space" (space, tab, and newline)
Example: StringTokenizer
Display the words separated by any of the following characters: space, new
line (\n), period (.) or comma (,).
String inputLine = keyboard.nextLine();
StringTokenizer wordFinder =
new StringTokenizer(inputLine, " \n.,");
//the second argument is a string of the 4 delimiters
while(wordFinder.hasMoreTokens())
{
System.out.println(wordFinder.nextToken());
}
Question
2b
Entering "Question,2b.or !tooBee." or
gives this output: !tooBee
Testing for End of File in a Text File
When readLine tries to read beyond the end of a text file it returns the
special value null
so you can test for null to stop processing a text file

read returns -1 when it tries to read beyond the end of a text file
the int value of all ordinary characters is nonnegative

Neither of these two methods (read and readLine) will throw an


EOFException.
Example: Using Null to
Test for End-of-File in a Text File
Excerpt from TextEOFDemo
When using
readLine
test for null int count = 0;
String line = inputStream.readLine();
while (line != null)
{
count++;
outputStream.println(count + " " + line);
line = inputStream.readLine();
}

When using read test for -1

Chapter 9 Java: an Introduction to Computer Science & Programming - Walter Savitch 109
Using Path Names
Path name—gives name of file and tells which directory the file is in
Relative path name—gives the path starting with the directory that the
program is in
Typical UNIX path name:
/user/smith/home.work/java/FileClassDemo.java
Typical Windows path name:
D:\Work\Java\Programs\FileClassDemo.java
When a backslash is used in a quoted string it must be written as two
backslashes since backslash is the escape character:
"D:\\Work\\Java\\Programs\\FileClassDemo.java"
Java will accept path names in UNIX or Windows format, regardless of
which operating system it is actually running on.
File Class [java.io]
Acts like a wrapper class for file names
A file name like "numbers.txt" has only String properties
File has some very useful methods
exists: tests if a file already exists
canRead: tests if the OS will let you read a file
canWrite: tests if the OS will let you write to a file
delete: deletes the file, returns true if successful
length: returns the number of bytes in the file
getName: returns file name, excluding the preceding path
getPath: returns the path name—the full name

File numFile = new File(“numbers.txt”);


if (numFile.exists())
System.out.println(numfile.length());
File Class [List all files in a folder]
import java.io.File;
import java.io.IOException;
public class ListOfFiles {
public static void main(String args[]) throws IOException {
//Creating a File object for directory
File directoryPath = new File("D:\ExampleDirectory");
//List of all files and directories
String contents[] = directoryPath.list();
System.out.println("List of files and directories in the specified directory:");
for(int i=0; i<contents.length; i++) {
System.out.println(contents[i]);
}
}
}
File Objects and Filenames
FileInputStream and FileOutputStream have constructors that take a
File argument as well as constructors that take a String argument

PrintWriter smileyOutStream = new PrintWriter(new


FileOutputStream(“smiley.txt”));

File smileyFile = new File(“smiley.txt”);


if (smileyFile.canWrite())
PrintWriter smileyOutStream = new PrintWriter(new
FileOutputStream(smileyFile));
Alternative with Scanner
Instead of BufferedReader with FileReader, then StringTokenizer
Use Scanner with File:
Scanner inFile =
new Scanner(new File(“in.txt”));
Similar to Scanner with System.in:
Scanner keyboard =
new Scanner(System.in);
Reading in int’s

Scanner inFile = new Scanner(new File(“in.txt"));


int number;
while (inFile.hasInt())
{
number = inFile.nextInt();
// …
}
Reading in lines of characters

Scanner inFile = new Scanner(new File(“in.txt"));


String line;
while (inFile.hasNextLine())
{
line = inFile.nextLine();
// …
}
Multiple types on one line
// Name, id, balance
Scanner inFile = new Scanner(new File(“in.txt"));
while (inFile.hasNext())
{
name = inFile.next();
id = inFile.nextInt();
balance = inFile.nextFloat();
// … new Account(name, id, balance);
}
--------------------
String line;
while (inFile.hasNextLine())
{
line = inFile.nextLine();
Scanner parseLine = new Scanner(line) // Scanner again!
name = parseLine.next();
id = parseLine.nextInt();
balance = parseLine.nextFloat();
// … new Account(name, id, balance);
}
Multiple types on one line
// Name, id, balance
Scanner inFile = new Scanner(new File(“in.txt"));
String line;
while (inFile.hasNextLine())
{
line = inFile.nextLine();
Account account = new Account(line);
}
--------------------
public Account(String line) // constructor
{
Scanner accountLine = new Scanner(line);
_name = accountLine.next();
_id = accountLine.nextInt();
_balance = accountLine.nextFloat();
}
BufferedReader vs Scanner
(parsing primitive types)

Scanner
nextInt(), nextFloat(), … for parsing types
BufferedReader
read(), readLine(), … none for parsing types
needs StringTokenizer then wrapper class methods like
Integer.parseInt(token)
BufferedReader vs Scanner
(Checking End of File/Stream (EOF))

BufferedReader
readLine() returns null
read() returns -1
Scanner
nextLine() throws exception
needs hasNextLine() to check first
nextInt(), hasNextInt(), …
BufferedReader inFile = …
line = inFile.readline();
while (line != null)
{
// …
line = inFile.readline();
}
-------------------
Scanner inFile = …
while (inFile.hasNextLine())
{
line = infile.nextLine();
// …
}
BufferedReader inFile = …
line = inFile.readline();
while (line != null)
{
// …
line = inFile.readline();
}
-------------------
BufferedReader inFile = …
while ((line = inFile.readline()) != null)
{
// …
}
My suggestion
Use Scanner with File
new Scanner(new File(“in.txt”))
Use hasNext…() to check for EOF
while (inFile.hasNext…())
Use next…() to read
inFile.next…()
Simpler and you are familiar with methods for Scanner
My suggestion cont…
File input
Scanner inFile =
new Scanner(new File(“in.txt”));
File output
PrintWriter outFile =
new PrintWriter(new File(“out.txt”));
outFile.print(), println(), format(), flush(), close(), …
Basic Binary File I/O
Important classes for binary file output (to the file)
ObjectOutputStream
FileOutputStream
Important classes for binary file input (from the file):
ObjectInputStream
FileInputStream
Note that FileOutputStream and FileInputStream are used only for
their constructors, which can take file names as arguments.
ObjectOutputStream and ObjectInputStream cannot take file
names as arguments for their constructors.
To use these classes your program needs a line like the following:
import java.io.*;
Java File I/O: Stream Classes
ObjectInputStream and ObjectOutputStream:
have methods to either read or write data one byte at a time
automatically convert numbers and characters into binary
binary-encoded numeric files (files with numbers) are not
readable by a text editor, but store data more efficiently
Remember:
input means data into a program, not the file
similarly, output means data out of a program, not the file
When Using ObjectOutputStream
to Output Data to Files:
The output files are binary and can store any of the primitive data types
(int, char, double, etc.) and the String type

The files created can be read by other Java programs but are not printable

The Java I/O library must be imported by including the line:


import java.io.*;
it contains ObjectOutputStream and other useful class
definitions

An IOException might be thrown


Handling IOException
IOException cannot be ignored
either handle it with a catch block
or defer it with a throws-clause

We will put code to open the file and write to it in a try-


block and write a catch-block for this exception :
catch(IOException e)
{
System.out.println("Problem with
output...";
}
Opening a New Output File

The file name is given as a String


file name rules are determined by your operating system

Opening an output file takes two steps


1. Create a FileOutputStream object associated with the file name
String
2. Connect the FileOutputStream to an ObjectOutputStream
object
This can be done in one line of code
Example: Opening an Output File
To open a file named numbers.dat:
ObjectOutputStream outputStream =
new ObjectOutputStream(
new FileOutputStream("numbers.dat"));

The constructor for ObjectOutputStream requires a FileOutputStream


argument
The constructor for FileOutputStream requires a String argument
the String argument is the output file name
The following two statements are equivalent to the single statement above:
FileOutputStream middleman =
new FileOutputStream("numbers.dat");
ObjectOutputStream outputStream =
new ObjectOutputSteam(middleman);
Some ObjectOutputStream Methods
You can write data to an output file after it is connected to a stream class
Use methods defined in ObjectOutputStream
writeInt(int n)
writeDouble(double x)
writeBoolean(boolean b)
etc.
See the text for more

Note that each write method throws IOException


eventually we will have to write a catch block for it

Also note that each write method includes the modifier final
final methods cannot be redefined in derived classes
Closing a File
An Output file should be closed when you are done writing to
it

Use the close method of the class


ObjectOutputStream

For example, to close the file opened in the previous example:


outputStream.close();

If a program ends normally it will close any files that are open
Writing a Character to a File: an Unexpected Little Complexity

The method writeChar has an annoying property:


it takes an int, not a char, argument

But it is easy to fix:


just cast the character to an int

For example, to write the character 'A' to the file opened previously:
outputStream.writeChar((int) 'A');

Or, just use the automatic conversion from char to int


Writing a boolean Value to a File
boolean values can be either of two values, true or
false

true and false are not just names for the values, they
actually are of type boolean

For example, to write the boolean value false to the


output file:
outputStream.writeBoolean(false);
Writing Strings to a File: Another Little Unexpected Complexity

Use the writeUTF method to output a value of type String


there is no writeString method
UTF stands for Unicode Text Format
a special version of Unicode
Unicode: a text (printable) code that uses 2 bytes per character
designed to accommodate languages with a different alphabet or no
alphabet (such as Chinese and Japanese)
ASCII: also a text (printable) code, but it uses just 1 byte per character
the most common code for English and languages with a similar alphabet
UTF is a modification of Unicode that uses just one byte for ASCII characters
allows other languages without sacrificing efficiency for ASCII files
When Using ObjectInputStream to Read Data from Files:

Input files are binary and contain any of the primitive data types (int, char,
double, etc.) and the String type

The files can be read by Java programs but are not printable

The Java I/O library must be imported including the line:


import java.io.*;
it contains ObjectInputStream and other useful class definitions

An IOException might be thrown


Opening a New Input File

Similar to opening an output file, but replace "output" with "input"

The file name is given as a String


file name rules are determined by your operating system

Opening a file takes two steps


1. Creating a FileInputStream object associated with the file name
String
2. Connecting the FileInputStream to an ObjectInputStream
object

This can be done in one line of code


Example: Opening an Input File
To open a file named numbers.dat:
ObjectInputStream inStream =
new ObjectInputStream (new
FileInputStream("numbers.dat"));
The constructor for ObjectInputStream requires a FileInputStream
argument
The constructor for FileInputStream requires a String argument
the String argument is the input file name
The following two statements are equivalent to the statement at the top of this
slide:
FileInputStream middleman =
new FileInputStream("numbers.dat");
ObjectInputStream inputStream =
new ObjectInputStream (middleman);
Some ObjectInputStream Methods
For every output file method there is a corresponding input file method

You can read data from an input file after it is connected to a stream class
Use methods defined in ObjectInputStream
readInt()
readDouble()
readBoolean()
etc.
See the text for more

Note that each write method throws IOException

Also note that each write method includes the modifier final
Input File Exceptions

A FileNotFoundException is thrown if the file is not found


when an attempt is made to open a file

Each read method throws IOException


we still have to write a catch block for it

If a read goes beyond the end of the file an EOFException is


thrown
Avoiding Common ObjectInputStream File Errors

There is no error message (or exception)


if you read the wrong data type!

Input files can contain a mix of data types


it is up to the programmer to know their order and use the
correct read method
ObjectInputStream works with binary, not text files
As with an output file, close the input file when you are done
with it
Common Methods to Test for the End of an Input File

A common programming situation is to read data from an input file


but not know how much data the file contains

In these situations you need to check for the end of the file

There are three common ways to test for the end of a file:
1. Put a sentinel value at the end of the file and test for it.
2. Throw and catch an end-of-file exception.
3. Test for a special character that signals the end of the file
(text files often have such a character).
The EOFException Class

Many (but not all) methods that read from a file throw an end-of-file exception
(EOFException) when they try to read beyond the file
all the ObjectInputStream methods in Display 9.3 do throw it

The end-of-file exception can be used in an "infinite" (while(true)) loop


that reads and processes data from the file
the loop terminates when an EOFException is thrown

The program is written to continue normally after the EOFException has


been caught
try
{
ObjectInputStream inputStream =

Using EOFException new ObjectInputStream(new FileInputStream("numbers.dat"));


int n;

System.out.println("Reading ALL the integers");


main method from System.out.println("in the file numbers.dat.");
EOFExceptionDemo try
{
while (true)
Intentional "infinite" loop to {
n = inputStream.readInt();
process data from input file System.out.println(n);
}
Loop exits when end-of- }
file exception is thrown catch(EOFException e)
{
System.out.println("End of reading from file.");
Processing continues }
after EOFException: inputStream.close();
}
the input file is closed catch(FileNotFoundException e)
{
System.out.println("Cannot find file numbers.dat.");
Note order of catch blocks: }
catch(IOException e)
the most specific is first {
and the most general last System.out.println("Problem with input from file numbers.dat.");
}

Chapter 9 Java: an Introduction to Computer Science & Programming - Walter Savitch 144
Binary I/O of Class Objects
read and write class objects in binary file

class must be serializable


import java.io.*
implement Serializable interface
add implements Serializable to heading of class definition
public class Species implements Serializable
methods used:

to write object to file: to read object from file:


writeObject method in readObject method in
ObjectOutputStream ObjectInputStream
outputStream = new ObjectOutputStream(
new FileOutputStream("species.records"));
...
Species oneRecord =
new Species("Calif. Condor, 27, 0.02);
...
outputStream.writeObject(oneRecord);

ClassIODemo Excerpts
inputStream = new ObjectInputStream(
new FileInputStream("species.records"));
... readObject returns a reference to
Species readOne = null; type Object so it must be cast to
... Species before assigning to readOne
readOne = (Species)inputStream.readObject(oneRecord);
The Serializable Interface
Java assigns a serial number to each object written out.
If the same object is written out more than once, after the
first write only the serial number will be written.
When an object is read in more than once, then there will be
more than one reference to the same object.
If a serializable class has class instance variables then they should
also be serializable.
Why aren't all classes made serializable?
security issues: serial number system can make it easier for
programmers to get access to object data
doesn't make sense in all cases, e.g., system-dependent data
Summary
Part 1
Text files contain strings of printable characters; they look
intelligible to humans when opened in a text editor.
Binary files contain numbers or data in non-printable codes; they
look unintelligible to humans when opened in a text editor.
Java can process both binary and text files, but binary files are
more common when doing file I/O.
The class ObjectOutputStream is used to write output to a
binary file.
Summary
Part 2
The class ObjectInputStream is used to read input from a
binary file.
Always check for the end of the file when reading from a file. The
way you check for end-of-file depends on the method you use to
read from the file.
A file name can be read from the keyboard into a String
variable and the variable used in place of a file name.
The class File has methods to test if a file exists and if it is read-
and/or write-enabled.
Serializable class objects can be written to a binary file.
THANK YOU
?

You might also like