Module2 Java File Handling and Exceptions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

1

FLEX Course Material


Understand various
files operations and
String manipulations
and properties
Implement custom
Java File
exceptions for handling
specific application
scenarios
Handling
Implement various
methods for reading
data from files
and
Explore different
techniques for writing
data to files
Exceptions
CCPRGG2L INTERMEDIATE PROGRAMMING
FOCAL POINTS

Understand various file operations and String


manipulations and properties;

Implement custom exceptions for handling specific


application scenarios

Implement various methods for reading data from


files

Explore different technique for writing data to files

?
INSIDE
• String manipulation
• Exception Handling
• File reading/writing

2
String Manipulations

In Java, a string is an object that represents a sequence of characters. It is


widely used data type for storing and manipulating textual data.

The String class in Java is provided as a part of the Java standard library
and offers various methods to perform operations on strings.

Strings are fundamental to Java programming and find extensive usage in


various applications, such as user input processing, text manipulation,
output formatting, and more.

Understanding the characteristics and capabilities of strings in Java is


essential for effective string manipulation and developing robust Java
applications.
String Manipulations

Java Strings
• Strings are used for storing text
• A String variable contains a collection of characters surrounded
by double quotes:

Example:

Create a variable of type String and assign it a value:

Output:
String Manipulations

String Length

• A String in Java is actually an object, which contain methods that


can perform certain operations on strings.
• It is used to find the length of a given string
• For example, the length of a string ca be found with the length()
method:

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

String “toUpperCase()” and “toLowerCase()”

• toUpperCase() converts a string to upper case letters while


toLowerCase() converts a string to lower case letters

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

All String Methods


The String class has a set of built-in methods that you can
use on strings.

Method Description Return Type


charAt() char
codePointAt() Returns the Unicode of the character at int
the specified index
codePointBefore() Returns the Unicode of the character int
before the specified index
codePointCount() Returns the number of Unicode values int
found in a string.
compareTo() Compares two strings lexicographically int
compareToIgnoreCase Compares two strings lexicographically, int
() ignoring case differences
concat() Appends a string to the end of another String
string
contains() Checks whether a string contains a boolean
sequence of characters
contentEquals() Checks whether a string contains the boolean
exact same sequence of characters of
the specified CharSequence or
StringBuffer
copyValueOf() Returns a String that represents the String
characters of the character array
endsWith() Checks whether a string ends with the boolean
specified character(s)
equals() Compares two strings. Returns true if boolean
the strings are equal, and false if not
equalsIgnoreCase() Compares two strings, ignoring case boolean
considerations
format() Returns a formatted string using the String
specified locale, format string, and
arguments
getBytes() Encodes this String into a sequence of byte[]
bytes using the named charset, storing
the result into a new byte array
getChars() Copies characters from a string to an void
array of chars
hashCode() Returns the hash code of a string int
indexOf() Returns the position of the first found int
occurrence of specified characters in a
string
intern() Returns the canonical representation String
for the string object
isEmpty() Checks whether a string is empty or not Boolean
String Manipulations

All String Methods (continuation)


Method Description Return Type
lastIndexOf() Returns the position of the last found occurrence of int
specified characters in a string
length() Returns the length of a specified string int
matches() Searches a string for a match against a regular boolean
expression, and returns the matches
offsetByCodePoints() Returns the index within this String that is offset from int
the given index by codePointOffset code points
regionMatches() Tests if two string regions are equal boolean
replace() Searches a string for a specified value, and returns a String
new string where the specified values are replaced
replaceFirst() Replaces the first occurrence of a substring that String
matches the given regular expression with the given
replacement
replaceAll() Replaces each substring of this string that matches the String
given regular expression with the given replacement
split() Splits a string into an array of substrings String[]
startsWith() Checks whether a string starts with specified characters boolean
subSequence() Returns a new character sequence that is a CharSequence
subsequence of this sequence
substring() Returns a new string which is the substring of a String
specified string
toCharArray() Converts this string to a new character array char[]
toLowerCase() Converts a string to lower case letters String
toString() Returns the value of a String object String
toUpperCase() Converts a string to upper case letters String
trim() Removes whitespace from both ends of a string String
valueOf() Returns the string representation of the specified value String
String Manipulations

Important Points to Note:


•String is a Final class; i.e once created the value cannot be altered. Thus String
objects are called immutable.

•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

•If a number is quoted in ” “ then it becomes a string, not a number anymore.


That means if
String S1 =”The number is: “+ “123”+”456″;
System.out.println(S1);
then it will print: The number is: 123456
If the initialization is like this:
String S1 = “The number is: “+(123+456);
System.out.println(S1);
then it will print: The number is:579
Exceptions Handling

What is Exception Handling?


• The Exception Handling in Java is one of the powerful mechanism to handle
the runtime errors so that the normal flow of the application can be
maintained.

• Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException, etc.

• In Java, an exception is an event that disrupts the normal flow of the


program. It is an object which is thrown at runtime.

• An exception is an unwanted or unexpected event that occurs during


program execution

Some possible reasons/causes of Exceptions:


• Accessing an array index that greater that the array size.
• Invalid data type.
• Invalid arithmetic operation.
• Invalid user input
• Device failure
• Code errors
• Opening an unavailable file
• Physical limitations (out of disk memory)
• Loss of network connection

Why do we need to handle Exceptions?

• To preserver/maintain the normal flow of the application. An exception


normally disrupts the normal flow of the application; that is why we need
to handle exceptions.
• To have meaningful error reporting
Exceptions Handling

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception
.
hierarchy inherited by two subclasses: Exception and Error. The
hierarchy of Java Exception classes is given below:
Exceptions Handling
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An
error is considered as the unchecked exception. However, according to
Oracle, there are three types of exceptions namely:

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

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The
following table describes each

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.

catch The "catch" block is used to handle the exception.


It must be preceded by try block which means we
can't use catch block alone. It can be followed by
finally block later.

finally The "finally" block is used to execute the


necessary code of the program. It is executed
whether an exception is handled or not.

throw The "throw" keyword is used to throw an


exception.
throws The "throws" keyword is used to declare
exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an
exception. It is always used with method
signature.
Exceptions Handling

Java try-catch block


Java try block

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.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch

try {
// Protected code or code that may throw exception
} catch (Exception_ClassName ref) {
// Catch block
}

Syntax of try-finally 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
}

Syntax of Java final 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
}

Internal Working of Java try-catch


block
Exceptions Handling

DEMO
JavaExceptionExample.java

Output:

Note: In the above example, 100/0 raises an


ArithmeticException which is handled by a try-catch block
Exceptions Handling

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

Java Files – What is File Handling?


• File handling is an important part of any application.

• Java has several methods for creating, reading, updating, and


deleting files.

• File reading / writing is a process of reading and/or writing a


resource. It is usually a text file. Each read line is considered a
String.

• Accessing a file always need exception handling.

Java File Handling

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:

import java.io.File; // Import the File class

File myObj = new File("filename.txt"); // Specify the


filename
File Reading / Writing

File class methods

createNewFile() - Creates an empty file.

delete() - Deletes a file.

exists() - Checks if a file exists.

getName() - Returns the name of the file

getAbsolutePath() - Returns the pathname of the file.

length() - Returns the size of the file in bytes

canWrite() – Tests whether the file is writable or not

canRead() – Tests whether the file is readable or not


File Reading / Writing

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:

File myObj = new File("C:\\Users\\MyName\\filename.txt");


File Reading / Writing

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:

import java.io.FileWriter; // Import the FileWriter class

import java.io.IOException; // Import the IOException class to handle errors

Output:
File Reading / Writing

Get File Information


To get more information about a file, use any of the File methods

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:

For simplicity, we are going to use:’

• 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.

BufferedReader class declaration

Below is the declaration for Java.io.BufferedReader class:


public class BufferedReader extends Reader

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.

BufferedReader class declaration


Below is the declaration for Java.io.BufferedWriter class:
public class BufferedWriter extends Writer

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.

The program is case sensitive.

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

1. Exception Handling. Retrieved November


26,2023 from
https://www.javatpoint.com/exception-
handling-in-java

2. Java files. Retrieved November 26,2023 from


https://www.w3schools.com/java/java_files.asp

3. Try_catch. Retrieved November 26,2023 from


https://www.w3schools.com/java/java_try_catc
h.asp

35

You might also like