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
✋

More Related Content

What's hot

Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
teach4uin
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Edureka!
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
Marcello Thiry
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streams
babak danyal
 
Java I/O
Java I/OJava I/O
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Wrapper classes
Wrapper classes Wrapper classes
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
Hitesh-Java
 
File handling
File handlingFile handling
File handling
priya_trehan
 
Generics
GenericsGenerics
Generics
Ravi_Kant_Sahu
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
Rohit Verma
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
Hitesh-Java
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
kumar gaurav
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 

What's hot (20)

Java interfaces
Java interfacesJava interfaces
Java interfaces
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streams
 
Java I/O
Java I/OJava I/O
Java I/O
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
File handling
File handlingFile handling
File handling
 
Generics
GenericsGenerics
Generics
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 

Similar to Basic i/o & file handling in java

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
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
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
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
HindAlmisbahi
 
Jstreams
JstreamsJstreams
asdabuydvduyawdyuadauysdasuydyudayudayudaw
asdabuydvduyawdyuadauysdasuydyudayudayudawasdabuydvduyawdyuadauysdasuydyudayudayudaw
asdabuydvduyawdyuadauysdasuydyudayudayudaw
WrushabhShirsat3
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
PragatiSutar4
 
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
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
MikialeTesfamariam
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
WondimuBantihun1
 
Java file
Java fileJava file
Java file
sonnetdp
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
SudhanshiBakre1
 
Java programming Chapter 4.pptx
Java programming Chapter 4.pptxJava programming Chapter 4.pptx
Java programming Chapter 4.pptx
ssusera0d3d2
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
9 Inputs & Outputs
9 Inputs & Outputs9 Inputs & Outputs
9 Inputs & Outputs
Deepak Hagadur Bheemaraju
 

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

Javaio
JavaioJavaio
Javaio
 
Javaio
JavaioJavaio
Javaio
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
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
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
Jstreams
JstreamsJstreams
Jstreams
 
asdabuydvduyawdyuadauysdasuydyudayudayudaw
asdabuydvduyawdyuadauysdasuydyudayudayudawasdabuydvduyawdyuadauysdasuydyudayudayudaw
asdabuydvduyawdyuadauysdasuydyudayudayudaw
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and output
 
Data file handling
Data file handlingData file handling
Data file handling
 
15. text files
15. text files15. text files
15. text files
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
Java file
Java fileJava file
Java file
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
Java programming Chapter 4.pptx
Java programming Chapter 4.pptxJava programming Chapter 4.pptx
Java programming Chapter 4.pptx
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
9 Inputs & Outputs
9 Inputs & Outputs9 Inputs & Outputs
9 Inputs & Outputs
 

Recently uploaded

clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
Bisnar Chase Personal Injury Attorneys
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 

Recently uploaded (20)

clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 

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