SlideShare a Scribd company logo
1 of 42
Download to read offline
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

Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVAAnkita Totala
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++Rabin BK
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Introduction to method overloading & method overriding in java hdm
Introduction to method overloading & method overriding  in java  hdmIntroduction to method overloading & method overriding  in java  hdm
Introduction to method overloading & method overriding in java hdmHarshal Misalkar
 
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...Edureka!
 
file handling c++
file handling c++file handling c++
file handling c++Guddu Spy
 
Java Basics
Java BasicsJava Basics
Java BasicsSunil OS
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword pptVinod Kumar
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionPritom Chaki
 

What's hot (20)

Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
 
Interface in java
Interface in javaInterface in java
Interface in java
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Introduction to method overloading & method overriding in java hdm
Introduction to method overloading & method overriding  in java  hdmIntroduction to method overloading & method overriding  in java  hdm
Introduction to method overloading & method overriding in java hdm
 
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Java program structure
Java program structure Java program structure
Java program structure
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 
file handling c++
file handling c++file handling c++
file handling c++
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaion
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 

Similar to Basic i/o & file handling in java

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
 
Java IO
Java IOJava IO
Java IO
 
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
 

Recently uploaded

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxabhijeetpadhi001
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 

Recently uploaded (20)

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 

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