EXCEPTION HANDLING AND
BASIC I/O AND
FILE HANDLING
TOPICS WE DISCUS
❏ EXCEPTION HANDLING
❏ GENERAL PRINCIPLES OF I/O
❏ JAVA FILE CLASS
❏ JAVA I/O API
❏ JAVA SCANNER CLASS
❏ JAVA SERIALIZATION
2
Exception Handling
3
What is an Exception?
An exception is an unexpected event that occurs during program
execution. It affects the flow of the program instructions which can
cause the program to terminate abnormally.
An exception can occur for many reasons. Some of them are:
● Invalid user input
● Device failure
● Loss of network connection
● Physical limitations (out of disk memory)
● Code errors
● Opening an unavailable file
4
Java Exception hierarchy
5
Exception, that means exceptional errors. Actually exceptions are
used for handling errors.Error that occurs during runtime .Cause
normal program flow to be disrupted
There is two type of Exception
Classifications
Unchecked- Occur in Run-time
Checked- Occur in Compile-time
Common Exceptions
Unchecked Exception
ArithmeticException--thrown if a program attempts to perform
division by zero
ArrayIndexOutOfBoundsException--thrown if a program
attempts to access an index of an array that does not exist
StringIndexOutOfBoundsException--thrown if a program
attempts to access a character at a non-existent index in a
String
NullPointerException--thrown if the JVM attempts to perform an
operation on an Object that points to no data, or null
6
Common Exceptions
NumberFormatException--thrown if a program is attempting to
convert a string to a numerical data type, and the string
contains inappropriate characters (i.e. 'z' or 'Q')
Checked Exceptions
ClassNotFoundException--thrown if a program can not find a
class it depends at runtime (i.e., the class's ".class" file cannot
be found or was removed from the CLASSPATH)
FileNotFoundException--when a file with the specified
pathname does not exist.
IOException--actually contained in java.io, but it is thrown if
the JVM failed to open an I/O stream
7
Exception Handling
In Java, we use the exception handler components try, catch and
finally blocks to handle exceptions.
To catch and handle an exception, we place the try...catch...finally
block around the code that might generate an exception. The finally
block is optional.
we can now catch more than one type of exception in a single catch
block.Each exception type that can be handled by the catch block is
separated using a vertical bar or pipe |.
catch (ExceptionType1 e1|ExceptionType2 e2) {
// catch block
}
8
Try Catch Finally
Try..catch block
try {
// code
} catch (ExceptionType e) {
// catch block
}
9
Try..catch..finally block
try {
// code
} catch (ExceptionType e) {
// catch block
} finally {
// finally block
}
throw, throws statement
Throw
The throw keyword is used to throw an exception explicitly. Only
object of Throwable class or its sub classes can be thrown. Program
execution stops on encountering throw statement, and the closest catch
statement is checked for matching type of exception
Throws
The throws keyword is used to declare the list of exception that a
method may throw during execution of program. Any method that is
capable of causing exceptions must list all the exceptions possible during
its execution, so that anyone calling that method gets a prior knowledge
about which exceptions are to be handled.
10
Error and Exception
An error is an irrecoverable condition occurring at runtime.
Though error can be caught in catch block but the execution of
application will come to a halt and is not recoverable.
While exceptions are conditions that occur because of bad input
etc.
In most of the cases it is possible to recover from an exception.
11
2.
General Principles Of I/O
12
Streams
All modern I/O is stream-based
A stream is a connection to a source of data or to a destination for
data (sometimes both)
An input stream may be associated with the keyboard
An input stream or an output stream may be associated with a file
Different streams have different characteristics:
A file has a definite length, and therefore an end
Keyboard input has no specific end
13
14
How TO Do
import java.io.*;
*Open the stream
*Use the stream
(read, write, or both)
*Close the stream
.
There is data external to your program that you want to get, or you
want to put data somewhere outside your program
When you open a stream, you are making a connection to that
external place
Once the connection is made, you forget about the external place
and just use the stream
Opening a Stream
15
Opening a Stream: Example
A FileReader is used to connect to a file that will be used for input:
FileReader fileReader = new FileReader (fileName);
The fileName specifies where the (external) file is to be found
You never use fileName again; instead, you use fileReader
16
Using a Stream
Some streams can be used only for input, others only for output,
still others for both
Using a stream means doing input from it or output to it
But it’s not usually that simple you need to manipulate the data in
some way as it comes in or goes out
17
Using a Stream :Example
int ch;
ch = FileReader.read( );
The FileReader.read() method reads one character and returns it
as an integer, or -1 if there are no more characters to read
The meaning of the integer depends on the file encoding (ASCII,
Unicode, other)
18
Using BufferReader
A BufferedReader will convert integers to characters; it can also
read whole lines
The constructor for BufferedReader takes a FileReader
parameter:
BufferedReader bufferedReader =
new BufferedReader(fileReader);
19
Closing
20
A stream is an expensive resource
There is a limit on the number of streams that you can have open at
one time
You should not have more than one stream open on the same file
You must close a stream before you can open it again
Always close your streams!
3.
JAVA FILE CLASS
21
File class
The File class in the Java IO API gives you access to the
underlying file system.
The File class is Java's representation of a file or directory path
name.
This class offers a rich set of static methods for reading, writing,
and manipulating files and directories.
The Files methods work on instances of Path objects
22
Operations in File class
The File class contains several methods for working with the path
name:
Check if a file exists.
Read the length of a file.
Rename or move a file/ Directory.
Delete a file/ Directory.
Check if path is file or directory.
Read list of files in a directory.
23
Creating a File object
You create a File object by passing in a String that represents the
name of a file.
For example,
File a = new File("/usr/local/bin/smurf");
This defines an abstract file name for the smurf file in
directory /usr/local/bin.
This is an absolute abstract file name.
You could also create a file object as follows:
File b = new File("bin/smurf");
This is a relative abstract file name
24
File Object Methods
Boolean exists() : Returns true if
the file exist.
Boolean canRead() : Returns true if
the file is readable.
Boolean canWrite() : Returns true
if the file is writable.
Boolean isAbsolute() : Returns true
if the file name is an absolute path
name.
25
Boolean isDirectory() : Returns
true if the file name is a directory.
Boolean isFile() : Returns true if
the file name is a "normal" file
(depends on OS)
Boolean isHidden() : Returns true
if the file is marked "hidden“.
long lastModified() : Returns a long
indicating the last time the file was
modified.
File Object Methods
long length() : Returns the length
of the contents of the file.
Boolean setReadOnly() : Marks
the file read-only (returns true if
succeeded)
void setLastModified(long) :
Explicitly sets the modification
time of a file
Boolean createNewFile() :
Creates a new file with this
abstract file name.
26
Returns true if the file was
created, false if the file already
existed.
Boolean delete(): Deletes the
file specified by this file name.
Boolean mkdir() : Creates this
directory.All parent directories
must already exist.
Boolean mkdirs() : Creates this
directory and any parent
directories that do not exist.
4.
JAVA I/O API
27
Reader class
The Reader class is the base class for all Reader's in the Java IO
API.
A Reader is like an InputStream except that it is character based
rather than byte based.
28
FileReader Class
Java FileReader class is used to read data from file .it return in
bytes format like FileInputstream.It is character-oriented class
which is used for file handling in java.
Object creation:
FileReader fr=new FileReader("path");
29
BufferedReader Class
Java BufferedReader class is used to read the text from a
character-based input stream. It can be used to read data line by
line by readLine() method. It makes the performance fast. It
inherits Reader class.
Object creation:
BufferedReader br= new BufferedReader();
30
Writer class
The Writer class is the base class for all Writer's in the Java IO
API.
A Writer is like an OutputStream except that it is character based
rather than byte based.
You will normally use a Writer subclass rather than a Writer
31
FileWritter Class
Java FileWriter class is used to write character-oriented data to a
file. It is character-oriented class which is used for file handling in
java.Unlike FileOutputStream class, you don't need to convert
string into byte array because it provides method to write string
directly.
Object creation:
FileWriter fw=new FileWriter("path");
32
BufferedWitter Class
Java BufferedWriter class is used to provide buffering for Writer
instances. It makes the performance fast. It inherits Writer class.
The buffering characters are used for providing the efficient
writing of single arrays, characters, and strings.
Object creation:
BufferedWritter bw= new BufferedWritter();
33
5.
JAVA Scanner Class
34
Scanner Class
Scanner class in Java is found in the java.util package. Java
provides various ways to read input from the keyboard, the
java.util.Scanner class is one of them.
The Java Scanner class is widely used to parse text for strings and
primitive types using a regular expression. It is the simplest way to
get input in Java. By the help of Scanner in Java, we can get input
from the user in primitive types such as int, long, double, byte,
float, short, etc.
35
Scanner Methods
For each of the primitive types there is a corresponding nextXxx()
method that returns a value of that type. If the string cannot be
interpreted as that type, then an InputMismatchException is
thrown.
int nextInt() : Returns the next token as an int.
long nextLong() : Returns the next token as a long.
float nextFloat() : Returns the next token as a float.
double nextDouble() : Returns the next token as a long.
36
Scanner Methods
String nextLine() : Returns the rest of the current line, excluding
any line separator at the end.
String next() : Finds and returns the next complete token from this
scanner and returns it as a string; a token is usually ended by
whitespace such as a blank or line break. If not token exists,
NoSuchElementException is thrown.
void close() : Closes the scanner.
37
Using a Scanner Class
To use the Scanner utility, we need to create an object.
Scanner Scan = new Scanner();
To get user input the above we need to use the system input
stream.
Scanner Scan = new Scanner( System.in );
The user input will be printed to the screen using the below
syntax.
System.out.println( Scan.nextLine() );
This will receive the input of the next line of text someone
types into the keyboard.
38
6.
Serialization
39
Object Serialization
Serialization in Java is a mechanism of writing the state of an
object into a byte-stream.
The reverse operation of serialization is called deserialization
where byte-stream is converted into an object. The serialization
and deserialization process is platform-independent, it means you
can serialize an object in a platform and deserialize in different
platform.
40
Using a Scanner Class
41
Serialization
Deserialization
Object Byte
Stream
Thanks!
Any questions?
42
✋

Basic i/o & file handling in java

  • 1.
    EXCEPTION HANDLING AND BASICI/O AND FILE HANDLING
  • 2.
    TOPICS WE DISCUS ❏EXCEPTION HANDLING ❏ GENERAL PRINCIPLES OF I/O ❏ JAVA FILE CLASS ❏ JAVA I/O API ❏ JAVA SCANNER CLASS ❏ JAVA SERIALIZATION 2
  • 3.
  • 4.
    What is anException? An exception is an unexpected event that occurs during program execution. It affects the flow of the program instructions which can cause the program to terminate abnormally. An exception can occur for many reasons. Some of them are: ● Invalid user input ● Device failure ● Loss of network connection ● Physical limitations (out of disk memory) ● Code errors ● Opening an unavailable file 4
  • 5.
    Java Exception hierarchy 5 Exception,that means exceptional errors. Actually exceptions are used for handling errors.Error that occurs during runtime .Cause normal program flow to be disrupted There is two type of Exception Classifications Unchecked- Occur in Run-time Checked- Occur in Compile-time
  • 6.
    Common Exceptions Unchecked Exception ArithmeticException--thrownif a program attempts to perform division by zero ArrayIndexOutOfBoundsException--thrown if a program attempts to access an index of an array that does not exist StringIndexOutOfBoundsException--thrown if a program attempts to access a character at a non-existent index in a String NullPointerException--thrown if the JVM attempts to perform an operation on an Object that points to no data, or null 6
  • 7.
    Common Exceptions NumberFormatException--thrown ifa program is attempting to convert a string to a numerical data type, and the string contains inappropriate characters (i.e. 'z' or 'Q') Checked Exceptions ClassNotFoundException--thrown if a program can not find a class it depends at runtime (i.e., the class's ".class" file cannot be found or was removed from the CLASSPATH) FileNotFoundException--when a file with the specified pathname does not exist. IOException--actually contained in java.io, but it is thrown if the JVM failed to open an I/O stream 7
  • 8.
    Exception Handling In Java,we use the exception handler components try, catch and finally blocks to handle exceptions. To catch and handle an exception, we place the try...catch...finally block around the code that might generate an exception. The finally block is optional. we can now catch more than one type of exception in a single catch block.Each exception type that can be handled by the catch block is separated using a vertical bar or pipe |. catch (ExceptionType1 e1|ExceptionType2 e2) { // catch block } 8
  • 9.
    Try Catch Finally Try..catchblock try { // code } catch (ExceptionType e) { // catch block } 9 Try..catch..finally block try { // code } catch (ExceptionType e) { // catch block } finally { // finally block }
  • 10.
    throw, throws statement Throw Thethrow keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can be thrown. Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception Throws The throws keyword is used to declare the list of exception that a method may throw during execution of program. Any method that is capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions are to be handled. 10
  • 11.
    Error and Exception Anerror is an irrecoverable condition occurring at runtime. Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable. While exceptions are conditions that occur because of bad input etc. In most of the cases it is possible to recover from an exception. 11
  • 12.
  • 13.
    Streams All modern I/Ois stream-based A stream is a connection to a source of data or to a destination for data (sometimes both) An input stream may be associated with the keyboard An input stream or an output stream may be associated with a file Different streams have different characteristics: A file has a definite length, and therefore an end Keyboard input has no specific end 13
  • 14.
    14 How TO Do importjava.io.*; *Open the stream *Use the stream (read, write, or both) *Close the stream .
  • 15.
    There is dataexternal to your program that you want to get, or you want to put data somewhere outside your program When you open a stream, you are making a connection to that external place Once the connection is made, you forget about the external place and just use the stream Opening a Stream 15
  • 16.
    Opening a Stream:Example A FileReader is used to connect to a file that will be used for input: FileReader fileReader = new FileReader (fileName); The fileName specifies where the (external) file is to be found You never use fileName again; instead, you use fileReader 16
  • 17.
    Using a Stream Somestreams can be used only for input, others only for output, still others for both Using a stream means doing input from it or output to it But it’s not usually that simple you need to manipulate the data in some way as it comes in or goes out 17
  • 18.
    Using a Stream:Example int ch; ch = FileReader.read( ); The FileReader.read() method reads one character and returns it as an integer, or -1 if there are no more characters to read The meaning of the integer depends on the file encoding (ASCII, Unicode, other) 18
  • 19.
    Using BufferReader A BufferedReaderwill convert integers to characters; it can also read whole lines The constructor for BufferedReader takes a FileReader parameter: BufferedReader bufferedReader = new BufferedReader(fileReader); 19
  • 20.
    Closing 20 A stream isan expensive resource There is a limit on the number of streams that you can have open at one time You should not have more than one stream open on the same file You must close a stream before you can open it again Always close your streams!
  • 21.
  • 22.
    File class The Fileclass in the Java IO API gives you access to the underlying file system. The File class is Java's representation of a file or directory path name. This class offers a rich set of static methods for reading, writing, and manipulating files and directories. The Files methods work on instances of Path objects 22
  • 23.
    Operations in Fileclass The File class contains several methods for working with the path name: Check if a file exists. Read the length of a file. Rename or move a file/ Directory. Delete a file/ Directory. Check if path is file or directory. Read list of files in a directory. 23
  • 24.
    Creating a Fileobject You create a File object by passing in a String that represents the name of a file. For example, File a = new File("/usr/local/bin/smurf"); This defines an abstract file name for the smurf file in directory /usr/local/bin. This is an absolute abstract file name. You could also create a file object as follows: File b = new File("bin/smurf"); This is a relative abstract file name 24
  • 25.
    File Object Methods Booleanexists() : Returns true if the file exist. Boolean canRead() : Returns true if the file is readable. Boolean canWrite() : Returns true if the file is writable. Boolean isAbsolute() : Returns true if the file name is an absolute path name. 25 Boolean isDirectory() : Returns true if the file name is a directory. Boolean isFile() : Returns true if the file name is a "normal" file (depends on OS) Boolean isHidden() : Returns true if the file is marked "hidden“. long lastModified() : Returns a long indicating the last time the file was modified.
  • 26.
    File Object Methods longlength() : Returns the length of the contents of the file. Boolean setReadOnly() : Marks the file read-only (returns true if succeeded) void setLastModified(long) : Explicitly sets the modification time of a file Boolean createNewFile() : Creates a new file with this abstract file name. 26 Returns true if the file was created, false if the file already existed. Boolean delete(): Deletes the file specified by this file name. Boolean mkdir() : Creates this directory.All parent directories must already exist. Boolean mkdirs() : Creates this directory and any parent directories that do not exist.
  • 27.
  • 28.
    Reader class The Readerclass is the base class for all Reader's in the Java IO API. A Reader is like an InputStream except that it is character based rather than byte based. 28
  • 29.
    FileReader Class Java FileReaderclass is used to read data from file .it return in bytes format like FileInputstream.It is character-oriented class which is used for file handling in java. Object creation: FileReader fr=new FileReader("path"); 29
  • 30.
    BufferedReader Class Java BufferedReaderclass is used to read the text from a character-based input stream. It can be used to read data line by line by readLine() method. It makes the performance fast. It inherits Reader class. Object creation: BufferedReader br= new BufferedReader(); 30
  • 31.
    Writer class The Writerclass is the base class for all Writer's in the Java IO API. A Writer is like an OutputStream except that it is character based rather than byte based. You will normally use a Writer subclass rather than a Writer 31
  • 32.
    FileWritter Class Java FileWriterclass is used to write character-oriented data to a file. It is character-oriented class which is used for file handling in java.Unlike FileOutputStream class, you don't need to convert string into byte array because it provides method to write string directly. Object creation: FileWriter fw=new FileWriter("path"); 32
  • 33.
    BufferedWitter Class Java BufferedWriterclass is used to provide buffering for Writer instances. It makes the performance fast. It inherits Writer class. The buffering characters are used for providing the efficient writing of single arrays, characters, and strings. Object creation: BufferedWritter bw= new BufferedWritter(); 33
  • 34.
  • 35.
    Scanner Class Scanner classin Java is found in the java.util package. Java provides various ways to read input from the keyboard, the java.util.Scanner class is one of them. The Java Scanner class is widely used to parse text for strings and primitive types using a regular expression. It is the simplest way to get input in Java. By the help of Scanner in Java, we can get input from the user in primitive types such as int, long, double, byte, float, short, etc. 35
  • 36.
    Scanner Methods For eachof the primitive types there is a corresponding nextXxx() method that returns a value of that type. If the string cannot be interpreted as that type, then an InputMismatchException is thrown. int nextInt() : Returns the next token as an int. long nextLong() : Returns the next token as a long. float nextFloat() : Returns the next token as a float. double nextDouble() : Returns the next token as a long. 36
  • 37.
    Scanner Methods String nextLine(): Returns the rest of the current line, excluding any line separator at the end. String next() : Finds and returns the next complete token from this scanner and returns it as a string; a token is usually ended by whitespace such as a blank or line break. If not token exists, NoSuchElementException is thrown. void close() : Closes the scanner. 37
  • 38.
    Using a ScannerClass To use the Scanner utility, we need to create an object. Scanner Scan = new Scanner(); To get user input the above we need to use the system input stream. Scanner Scan = new Scanner( System.in ); The user input will be printed to the screen using the below syntax. System.out.println( Scan.nextLine() ); This will receive the input of the next line of text someone types into the keyboard. 38
  • 39.
  • 40.
    Object Serialization Serialization inJava is a mechanism of writing the state of an object into a byte-stream. The reverse operation of serialization is called deserialization where byte-stream is converted into an object. The serialization and deserialization process is platform-independent, it means you can serialize an object in a platform and deserialize in different platform. 40
  • 41.
    Using a ScannerClass 41 Serialization Deserialization Object Byte Stream
  • 42.