Module2 Java File Handling and Exceptions
Module2 Java File Handling and Exceptions
Module2 Java File Handling and Exceptions
?
INSIDE
• String manipulation
• Exception Handling
• File reading/writing
2
String Manipulations
The String class in Java is provided as a part of the Java standard library
and offers various methods to perform operations on strings.
Java Strings
• Strings are used for storing text
• A String variable contains a collection of characters surrounded
by double quotes:
Example:
Output:
String Manipulations
String Length
Example:
Output:
String Manipulations
String “indexOf”
• It is the method that returns the index (the position) of the first
occurrence of a specified text in a string (including whitespace)
Example:
Output:
String Manipulations
Example:
Output:
String Manipulations
String Concatenation
• It is the method used to combine strings. It can be done by using
+ operator and concat() method
Example:
Output:
Example:
Output:
String Manipulations
•The Java Virtual Machine(JVM) creates a memory location especially for Strings
called String Constant Pool. That’s why String can be initialized without ‘new’
keyword.
•String class falls under java.lang.String hierarchy. But there is no need to import
this class. Java platform provides them automatically.
•String reference can be overridden but that does not delete the content; i.e., if
String h1 = “hello”;
h1 = “hello”+”world”;
then “hello” String does not get deleted. It just loses its handle.
•Multiple references can be used for same String but it will occur in the same
place; i.e., if
String h1 = “hello”;
String h2 = “hello”;
String h3 = “hello”;
then only one pool for String “hello” is created in the memory with 3 references-
h1,h2,h3
1) Checked Exception
• Exception that is checked (notified) by the compiler at compilation –
time (a.k.a. compile-time error)
• The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions.
• For example, FileNotFoundException, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
• Exception that occurs during the code execution (a.k.a. runtime error)
• The classes that inherit the RuntimeException are known as unchecked
exceptions.
• For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc.
• Unchecked exceptions are not checked at compile-time, but they are
checked at runtime.
3) Error
• These are not exceptions at all, but problems that arise beyond the
control of the user or the programmer
• Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Exceptions Handling
Categories of Java Exceptions
Keyword Description
try The "try" keyword is used to specify a block where
we should place an exception code. It means we
can't use try block alone. The try block must be
followed by either catch or finally.
Java try block is used to enclose the code that might throw an exception. It
must be used within the method.
If an exception occurs at the particular statement in the try block, the rest of
the block code will not execute. So, it is recommended not to keep the code in
try block that will not throw an exception.
try {
// Protected code or code that may throw exception
} catch (Exception_ClassName ref) {
// Catch block
}
try {
// Protected code or code that may throw exception
} finally {
// Catch block
}
Exceptions Handling
Syntax of Java Multiple try-catch
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
} catch (ExceptionName e1) {
// Catch block
}
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
} catch (ExceptionName e2) {
// can have more than one catch. Same with if- else if – else concept
} finally {
// This will always be executed
}
DEMO
JavaExceptionExample.java
Output:
DEMO
TryCatchExample9.java
Output:
Exceptions Handling
DEMO
Main.java
The finally statement lets you execute code, after try...catch, regardless of the result:
Output:
Exceptions Handling
DEMO
Example to handle checked exception.
Output:
File Reading / Writing
The File class from the java.io package, allows us to work with
files.
To use the File class, create an object of the class, and specify
the filename or directory name:
Create a File
To create a file in Java, you can use the createNewFile() method.
This method returns a boolean value: true if the file was successfully created,
and false if the file already exists.
Note that the method is enclosed in a try...catch block. This is necessary because
it throws an IOException if an error occurs (if the file cannot be created for some
reason)
Example:
Output:
Note: To create a file in a specific directory (requires permission), specify the path of
the file and use double backslashes to escape the " \" character (for Windows). On Mac
and Linux you can just write the path, like: /Users/name/filename.txt
Example:
Write To a File
In the following example, we use the FileWriter class together with
its write() method to write some text to the file we created in the example
above.
Note that when you are done writing to the file, you should close it with
the close() method:
Example:
Output:
File Reading / Writing
Example:
Output:
File Reading / Writing
Delete a File
To delete a file in Java, use the delete() method:
Example:
Output:
File Reading / Writing
Delete a Folder
You can also delete a folder. However, it must be empty
Example:
Output:
File Reading / Writing
There are many available classes in the Java API that can be used to
read and write files in Java:
• BufferedReader
• BufferedWriter
• FileReader
• FileWriter
BufferedReader Class
• it is a 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.
Example:
Output
In this example, we are reading the data from the text file testout.txt using Java
BufferedReader class.
Here, we are assuming that you have following data in "testout.txt" file:
File Reading / Writing
BufferedWriter Class
• It is a class 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.
Example:
Output:
In this example, we are wrtiing the data from the text file testout.txt using Java
BufferedWriterclass.
Here, we are assuming that you have following data in "testout.txt" file:
File Reading / Writing
File Reading / Writing
Activity 2.1
Assume you have a file containing the ff text:
Juan Limbo
Al Laure
Kenzo Sardea
Gabriel Macato
Joshua Manalansan
Create a program that asks for a username and password. The program should
read the text contained in the txt file. The first word represents the username and
the second represents the respective password. If the username and password is
correct, display “Successfully entered the program”. Otherwise display Invalid
Username or Invalid Password.
Sample run1:
Enter username: Bianca
Output: Invalid username
Sample run 2:
Enter username: Al
Ener password: Joseph
Output: Invalid Password
Sample run 3:
Enter username: Gabriel
Enter password: Macato
Output: Successfully entered the program
File Reading / Writing
Activity 2.2
Revise the first program by adding a limit on the number of attempts for the
username and password. The user will be asked to enter the correct username
and password for 3 times. If the limit is reached, the program will have to end.
Activity 2.3
Revise again the program by allowing the user to enter a new username and
password after successfully logging-in to the system.
The new username and password should append
Scenario:
Enter a new username: Juan
Enter a new Password: dela Cruz
REFERENCES
35