SlideShare a Scribd company logo
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
✋
Ad

More Related Content

What's hot (20)

Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
File handling
File handlingFile handling
File handling
priya_trehan
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
Applets in java
Applets in javaApplets in java
Applets in java
Wani Zahoor
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Java I/O
Java I/OJava I/O
Java I/O
Jussi Pohjolainen
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
Om Ganesh
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
pm2214
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
Madishetty Prathibha
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
Binay Kumar Ray
 
Java threads
Java threadsJava threads
Java threads
Prabhakaran V M
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
Math-Circle
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
History of java'
History of java'History of java'
History of java'
deepthisujithra
 
Java Notes
Java NotesJava Notes
Java Notes
Abhishek Khune
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
Kongu Engineering College, Perundurai, Erode
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
Files in java
Files in javaFiles in java
Files in java
Muthukumaran Subramanian
 
Python - An Introduction
Python - An IntroductionPython - An Introduction
Python - An Introduction
Swarit Wadhe
 

Similar to Basic i/o & file handling in java (20)

Javaio
JavaioJavaio
Javaio
Jaya Jeswani
 
Javaio
JavaioJavaio
Javaio
Jaya Jeswani
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
Kavitha713564
 
chapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and streamchapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
Kongunadu College of Engineering and Technology
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File Concepts
ANUSUYA S
 
UNIT 5 PY.pptx - FILE HANDLING CONCEPTS
UNIT 5 PY.pptx   -  FILE HANDLING CONCEPTSUNIT 5 PY.pptx   -  FILE HANDLING CONCEPTS
UNIT 5 PY.pptx - FILE HANDLING CONCEPTS
drkangurajuphd
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
HindAlmisbahi
 
Jstreams
JstreamsJstreams
Jstreams
Shehrevar Davierwala
 
asdabuydvduyawdyuadauysdasuydyudayudayudaw
asdabuydvduyawdyuadauysdasuydyudayudayudawasdabuydvduyawdyuadauysdasuydyudayudayudaw
asdabuydvduyawdyuadauysdasuydyudayudayudaw
WrushabhShirsat3
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
PragatiSutar4
 
IO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon pptIO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
NilaNila16
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and output
Riccardo Cardin
 
Data file handling
Data file handlingData file handling
Data file handling
Prof. Dr. K. Adisesha
 
15. text files
15. text files15. text files
15. text files
Konstantin Potemichev
 
Absolute Java 5th Edition Walter Savitch Solutions Manual
Absolute Java 5th Edition Walter Savitch Solutions ManualAbsolute Java 5th Edition Walter Savitch Solutions Manual
Absolute Java 5th Edition Walter Savitch Solutions Manual
labakybrasca33
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
MikialeTesfamariam
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
WondimuBantihun1
 
Ad

Recently uploaded (20)

Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Ad

Basic i/o & file handling in java

  • 1. EXCEPTION HANDLING AND BASIC I/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
  • 4. 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
  • 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--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
  • 7. 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
  • 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..catch block 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 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
  • 11. 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
  • 13. 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. 14 How TO Do import java.io.*; *Open the stream *Use the stream (read, write, or both) *Close the stream .
  • 15. 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
  • 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 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
  • 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 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
  • 20. 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!
  • 22. 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
  • 23. 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
  • 24. 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
  • 25. 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.
  • 26. 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.
  • 28. 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
  • 29. 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
  • 30. 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
  • 31. 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
  • 32. 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
  • 33. 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
  • 35. 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
  • 36. 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
  • 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 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
  • 40. 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
  • 41. Using a Scanner Class 41 Serialization Deserialization Object Byte Stream