0% found this document useful (0 votes)
13 views12 pages

Chapter Three Revised

This document discusses exception handling and file I/O streams in Java, explaining how exceptions are errors during program execution that can be managed using keywords like try, catch, and finally. It also covers the importance of file I/O for data persistence, detailing byte-based and character-based streams, and introduces classes like OutputStream and InputStream for handling file operations. Additionally, it explains object serialization and deserialization using ObjectOutputStream and ObjectInputStream for saving and retrieving objects from files.

Uploaded by

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

Chapter Three Revised

This document discusses exception handling and file I/O streams in Java, explaining how exceptions are errors during program execution that can be managed using keywords like try, catch, and finally. It also covers the importance of file I/O for data persistence, detailing byte-based and character-based streams, and introduces classes like OutputStream and InputStream for handling file operations. Additionally, it explains object serialization and deserialization using ObjectOutputStream and ObjectInputStream for saving and retrieving objects from files.

Uploaded by

ammolys
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Exception Handling and File IO Stream

Chapter 3
Exception Handling and Files IO Streams
What is an exception?
An exception is an error that occurs during the execution of a program. The exception handling
in java is one of the powerful mechanisms to handle the runtime errors so that normal flow of
the application can be maintained. Java facilitates the management of such errors by diverting
control to special program bocks that are called exception handlers.
Exception handling enables programmers to create applications that can resolve (or handle)
exceptions. In many cases, handling an exception allows a program to continue executing as if
no problem had been encountered. These features enable programmers to write robust and fault-
tolerant programs.

The causes of exception


1. Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
Eample int a=50/0;//ArithmeticException
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
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.
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 Keywords


Java provides five keywords that are used to handle the exception. The following table describes
each.

Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code.
It means we can't use try block alone.
The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception.
It must be preceded by try block which means we can't use catch block alone.
It can be followed by finally block later.
1|Page
Exception Handling and File IO Stream

finally The "finally" block is used to execute the necessary


code of the program. It is executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions.
It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always
used with method signature.

 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.
try{ //code that may throw an exception }
catch(Exception_class_Name ref){}

 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.

 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.
 The syntax of java throw keyword is given below.

Example:- Scenario where ArithmeticException occurs


package trycatchexample;
public class TryCatchExample {
public static void main(String[] args) {
// TODO code application logic here
int i=50;
int j=1;
int data;
try
{ j--;
data=i/j; //may throw exception
System.out.println("the value=" +data);
} // handling the exception
2|Page
Exception Handling and File IO Stream

catch(ArithmeticException e)
{ // resolving the exception in catch block
System.out.println(i/(j+2));
System.out.println(e);
} }}
Example :- Scenario where ArrayIndexOutOfBoundsException occurs

package testexce;
public class TestEXce {
public static void main(String[] args) {
int[] ar={5,4,8,6};
int i=0;
try{
for(i=4;i>=0;i--)
System.out.println("Array ["+i+"] = "+ar[i]);
}
catch(Exception e){
System.out.println("Array ["+i+"] = "+8);
System.out.println(e);
}}}
Example:- on throw keyword.
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..."); } }
 Java throws keyword
 The Java throws keyword is used to declare an exception.
 It gives 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 Null PointerException, it is
programmers fault that he is not performing checkup before the code being used

3|Page
Exception Handling and File IO Stream

Introduction Files IO Streams


Data stored in variables and arrays are temporary. This means it will be lost when a local
variable goes out of scope or when the program execution terminates. Therefore, for long-term
retention of data, even after the programs that create the data terminate, computers use files. We
use files every day for tasks such as writing a document or creating a spreadsheet. Computers
store files on secondary storage devices, including hard disks, flash drives, DVDs and more.
Data maintained in files is persistent data and it exists beyond the duration of program
execution. In this chapter, we explain how Java programs create, update and process files begin
with a discussion of Java’s architecture for handling files programmatically. Next we explain that
data can be stored in text files and binary files covering the differences between them.

File and Stream


Java views each file as a sequential stream of bytes. A Java program processing stream of bytes,
simply receives an indication from the operating system when it reaches the end of the stream.
 Byte-Based and Character-Based Streams
 File streams can be used to input and output data as bytes or characters.
 Byte-based streams output and input data in its binary format a char is two bytes, an
int is four bytes, a double is eight bytes, etc.
 Character-based streams output and input data as a sequence of characters in which
every character is two bytes
 The number of bytes for a given value depends on the number of characters in that
value. For example, the value 2000000000 requires 20 bytes (10 characters at two
bytes per character) but the value 7 requires only two bytes (1 character at two bytes
per character).
Files created using byte-based streams are referred to as binary files, while files created using
character-based streams are referred to as text files. Text files can be read by text editors, while
binary files can be read by programs that understand the file’s specific content and ordering. A
numeric value in a binary file can be used in calculations, whereas the character 5 is simply a
character that can be used in a string of text, as in "Sarah Miller is 15 years old".
Java I/O classes
In java there are two main classes for processing files. These are:-
1. OutputStream class
2. InputStream class
1. OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to specific output
terminals using the following methods. Note how the write() method is overloaded.
Useful methods of OutputStream
Method Description
1) public void write(int)throws is used to write a byte to the current output stream.
IOException
2) public void write(byte[])throws is used to write an array of byte to the current
IOException output stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException is used to close the current output stream.
4|Page
Exception Handling and File IO Stream

OutputStream Hierarchy
The structure of outputstream classes in java can be summarized as in the diagram below.

2. InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes. There are some useful methods to use a file as an input terminal in java program.
The methods are described in table below. Useful methods of InputStream
Method Description
1) public abstract int read()throws reads the next byte of data from the input stream. It
IOException returns -1 at the end of the file.
2) public int available()throws returns an estimate of the number of bytes that can be
IOException read from the current input stream.
3) public void close()throws is used to close the current input stream.
IOException

Java FileOutputStream example

5|Page
Exception Handling and File IO Stream

import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to java file.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}
catch(Exception e){
System.out.println(e);}
} }
In the above program, the content of a text file testout.txt is set with the data Welcome to java
file. in the D directory.
Java FileInputStream example

package com.javatpoint;
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i); }
fin.close();
} catch(Exception e){
System.out.println(e);}
} }
In the above program, the content of a text file testout.txt is read and the data Welcome to java
file. will be displayed to the console.

java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark" Java
classes so that the objects of these classes may get a certain capability. It must be implemented
by the class whose object you want to persist/save to a file.
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java objects to an
OutputStream. Only objects that support the java.io.Serializable interface can be written to
streams.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the
methods for serializing and deserializing an object. The ObjectOutputStream class contains
many write methods for writing various data types, but one method in particular stands out.
6|Page
Exception Handling and File IO Stream

Constructor

1) public ObjectOutputStream(OutputStream creates an ObjectOutputStream that


out) throws IOException {} writes to the specified OutputStream.

Important Methods

Method Description
1) public final void writeObject(Object obj) writes the specified object to the
throws IOException {} ObjectOutputStream.
2) public void flush() throws IOException {} flushes the current output stream.
3) public void close() throws IOException {} closes the current output stream.
ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.
Constructor
1) public ObjectInputStream(InputStream in) creates an ObjectInputStream that reads
throws IOException {} from the specified InputStream.

Important Methods

Method Description
1) public final Object readObject() throws IOException, reads an object from the input
ClassNotFoundException{} stream.
2) public void close() throws IOException {} closes ObjectInputStream.

public final void writeObject(Object x) throws IOException

The above method serializes an Object and sends it to the output stream. Similarly, the
ObjectInputStream class contains the following method for deserializing an object

public final Object readObject() throws IOException, ClassNotFoundException

This method retrieves the next Object out of the stream and deserializes it. The return value is
Object, so you will need to cast it to its appropriate data type.

Serializing an Object
Java provides a mechanism, called object serialization where an object can be represented as a
sequence of bytes that includes the object's data as well as information about the object's type
and the types of data stored in the object. After a serialized object has been written into a file, it
can be read from the file and deserialized that is, the type information and bytes that represent
the object and its data can be used to recreate the object in memory.
7|Page
Exception Handling and File IO Stream

The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo


program instantiates an Employee object and serializes it to a file. When the program is done
executing, a file named employee.ser is created. The program does not generate any output, but
study the code and try to determine what the program is doing.
Note:- When serializing an object to a file, the standard convention in Java is to give the file a
.ser extension.
Example
//import java.io.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream
import java.io.Serializable;
class Employee implements Serializable {
String name;
String address;
int SSN;
int number;}

public class SerializeDemo {


public static void main(String [] args) {
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try {
FileOutputStream fileOut =new FileOutputStream("D:\\employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in D:\\employee.ser");
} catch (IOException i) {
i.printStackTrace();
} }}
In the example below, we are going to serialize the object of Student class. The writeObject()
method of ObjectOutputStream class provides the functionality to serialize the object. We are
saving the state of the object in the file named f.txt.
import java.io.*;
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
8|Page
Exception Handling and File IO Stream

this.name = name; } }
class Persist{
public static void main(String args[]){
try{
//Creating the object
Student s1 =new Student(211,"ravi");
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
System.out.println("success serialization");
}catch(Exception e){System.out.println(e);}
}
}

Deserializing an Object
Deserialization is the process of reconstructing the object from the serialized state. It is the
reverse operation of serialization. Let's see an example where we are reading the data from a
deserialized object. The following DeserializeDemo program deserializes the Employee object
created in the SerializeDemo program. Study the program and try to determine its output
Example 1.
import java.io.*;
class Employee implements Serializable {
String name;
String address;
int SSN;
int number;}

public class DeserializeDemo {


public static void main(String [] args) {
Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("D:\\employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
9|Page
Exception Handling and File IO Stream

return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number); }}

This will produce the following result −


Output
Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101

Example2.
import java.io.*;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name; } }

class Depersist{
public static void main(String args[]){
try{
//Creating stream to read the object
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject(); //printing the data of the serialized object
System.out.println(s.id+" "+s.name);
//closing the stream
in.close();
}catch(Exception e){System.out.println(e);}
}
}

The output.
211 ravi
Here are following important points to be noted in the example1 above.
 The try/catch block tries to catch a ClassNotFoundException, which is declared by the
readObject() method. For a JVM to be able to deserialize an object, it must be able to find
the bytecode for the class. If the JVM can't find a class during the deserialization of an
object, it throws a ClassNotFoundException.
 Notice that the return value of readObject() is cast to an Employee reference.
10 | P a g e
Exception Handling and File IO Stream

 The value of the SSN field was 11122333 when the object was serialized, but because the
field is transient, this value was not sent to the output stream. The SSN field of the
deserialized Employee object is 0.

Stream Tokenizers
You can write an auxiliary method that decomposes a string into its tokens, but this task arises in
a specific case. Java language designers have devised a helper class, classStringTokenizer
(found in the package, java.util), that contains methods for de-composing strings into tokens.
Strings = "$13.46";
StringTokenizer t = new StringTokenizer(s,"$.");
String dollars= t.nextToken();
String cents= t.nextToken();
The second statement creates a string tokenizer that considers both $and. to be legal delimiters
.A string tokenizer can use multiple distinct delimiters, and the delimiters are packaged as a
string to the tokenizer's constructor method.

Sequential Access Text file

To keep things simple, we will work with text files and how to read and write streams of data
into them. Because Java does not impose any structure while manipulating sequential access to a
file, so, it is the responsibility of the programmer to establish a structure, meaning, how the data
will be stored in the file. Therefore, the programmer must structure files for instance into rows
and columns to meet the requirements of a specific application. The Formatter class of
java.util.Formatter package can support Sequential Access Text file as in example below.

package fileformatter;
import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class FileFormatter {
private static Formatter output; // outputs text to a file
public static void main(String[] args) {
// TODO code application logic here
openFile();
addRecords();
closeFile();
}
// open file clients.txt
public static void openFile()
{ try
{
output = new Formatter("D:\\clients.txt"); // open the file }
catch (SecurityException securityException)
{
System.err.println("Write permission denied. Terminating.");
11 | P a g e
Exception Handling and File IO Stream

System.exit(1); // terminate the program }


catch (FileNotFoundException fileNotFoundException)
{
System.err.println("Error opening file. Terminating.");
System.exit(1); // terminate the program
} }
// add records to file
public static void addRecords()
{
Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n? ",
"Enter account number, first name, last name and balance.",
"Enter end-of-file indicator to end input.");
while (input.hasNext()) // loop until end-of-file indicator
{
try
{
output.format("%d %s %s %.2f%n", input.nextInt(),
input.next(), input.next(), input.nextDouble());}
catch (FormatterClosedException formatterClosedException)
{
System.err.println("Error writing to file. Terminating.");
break; }
catch (NoSuchElementException elementException)
{
System.err.println("Invalid input. Please try again.");
input.nextLine(); // discard input so user can try again
}
System.out.print("? ");
} // end while
} // end method addRecords
public static void closeFile()
{
if (output != null)
output.close();
} }
The above program writes rows and columns data to the specified file D:\\clients.txt. the program
used to read the file is in your text book and left for you to refer.
Note:- Files can be read/written in two ways:-
1. A sequential file must be read (or written) from front to back; it is like a book whose
pages can be turned in only one direction forwards.
2. A random access file allows reads (or writes) at any place within it; it is like a normal book that
can be opened to any particular page number.

12 | P a g e

You might also like