0% found this document useful (0 votes)
42 views

Unit 3 - v4

This document provides an overview of exceptions in programming fundamentals II. It defines exceptions as unexpected runtime conditions and discusses exception handling. Key points include: - Exceptions can end a program or be handled to allow continuation. - Java uses try-catch blocks to handle exceptions, with catch blocks for specific exception types. - Checked exceptions must be caught or declared as thrown, while unchecked exceptions represent program bugs. - Methods can declare multiple exception types using throws. - Try-with-resources was introduced in Java 7 to automatically close resources like files.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Unit 3 - v4

This document provides an overview of exceptions in programming fundamentals II. It defines exceptions as unexpected runtime conditions and discusses exception handling. Key points include: - Exceptions can end a program or be handled to allow continuation. - Java uses try-catch blocks to handle exceptions, with catch blocks for specific exception types. - Checked exceptions must be caught or declared as thrown, while unchecked exceptions represent program bugs. - Methods can declare multiple exception types using throws. - Try-with-resources was introduced in Java 7 to automatically close resources like files.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Programming Fundamentals II

UNIT 3. EXCEPTIONS

A. Niño. Universidad de Castilla-La Mancha


Bibliography
UNIT 3. EXCEPTIONS
Basic references
-Muñoz Caro C., Niño A. y Vizcaíno Barceló A. Introducción a la programación
con orientación a objetos. Chapter 9. Prentice-Hall, 2002. Reimpresión 2007.

- P. S. Nair. Java. Programming Fundamentals. Chapter 11. CRC Press (Taylor &
Francis Group), 2009. ISBN-13:978-1-4200-6547-3.

- JAVA tutorial:
http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 2


Outline
UNIT 3. EXCEPTIONS
3.1. Introduction
3.2. Exceptions concept
3.3. Handling exceptions
3.4. Creating new exceptions
3.5. JAVA exceptions hierarchy
3.6. Files in Java and their exceptions
3.6.1. Sequential text files
3.6.2. Random access text files

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 3


3.1. Introduction (I)
 An exception is usually an unexpected condition that
occurs at runtime. This condition usually ends the program
with an error message. Typical examples: non-existence of
a file or directory, division by zero, memory exhaustion,
etc… The definition of these errors and how they are
handled may be defined by the programmer.

 Exception handling is provided in programming


languages such as C++ or JAVA.

 In this unit we introduce the concept of exception and the


capture mechanism and management of Java exceptions.

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 4


3.1. Introduction (II)
 After presenting the mechanism of exceptions, we will
remind text files in Java (seen in Programming
Fundamentals I) and their associated exceptions.

 Next, random access files and their exceptions will be


presented, as well.

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 5


3.2 Exceptions concept (I)
 An exception is a runtime unusual condition

 The program can detect the problem and act accordingly


to solve it. If the program does not control the exception
the program will terminate. If we wish to handle the error,
the program can catch the exception and continues the
execution by using exception handling tools provided by
your programming language.

 When an exception occurs in a program and the exception


handler for this exception is active, the control flow is
transferred to the handler. Otherwise, the program ends up
with an error condition.

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 6


3.2 Exceptions concept (II)
 When exceptions are managed, three different scenarios
are possible:
 The program ends.

 The error is corrected and the program continues.

 The error is recorded and the program continues.

 The programmer has to decide what action should be


taken depending on the kind of problem.

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 7


3.3. Handling exceptions (I)
 An exception is handled by sending the program execution
to a specific piece of code known as the "exception
handler". Depending on the exception type, the handler
can allow the program to continue running or to terminate.
We shall now introduce the JAVA exception capture and
management mechanism.

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 8


3.3. Handling exceptions (II)
 Exceptions always occur in a method. The method throws
an exception that can be captured. The try-catch statement
is used to catch exceptions in JAVA.
 The first step in constructing an exception handler is to
enclose the code that might throw an exception within a try
block.
 The catch block contains code that is executed if and when
the exception handler is invoked. Each catch block is an
exception handler and handles the type of exception
indicated by its argument.

 As many catch blocks as possible exceptions can be


written. Let’s see the syntax:

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 9


3.3. Handling exceptions (III)

try {
--- block of statements that can produce the problem ---
}
catch (TypeOfException1 e1) {
--- block of statements in case of TypeOfException1 ---
}
...
catch (TypeOfExceptionN eN) {
--- block of statements in case of TypeOfExceptionN ---
}
finally { //optional
--- block of code that is always executed ---
}

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 10


3.3. Handling exceptions (IV)
 Exceptions are classes in JAVA. Therefore, in addition to
the name of each exception, an identifier is also included.
This identifier is a reference of the exception class and its
name is arbitrary. For this reason, an “e” is frequently used
as exception name.

 When an exception is thrown in a method, the program


control leaves the try block and examines the catch in
search for the block that corresponds to this exception. If it
is found, it is executed. The control flow then jumps to the
finally block, if any, or comes back to the code.

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 11


3.3. Handling exceptions (V)
 If an exception is not caught using the try-catch block the
exception is propagated among methods. It is first
propagated to the calling method. If it is not captured, the
exception is propagated to the method that it was called by,
and so on until it is sent to the method that began the
execution (main method). Finally, if it is not caught, the
program ends with an error.

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 12


3.3. Handling exceptions (VI)
 JAVA has two kinds of exceptions:
 Unchecked exceptions. These represent defects in the
program (bugs), often invalid arguments passed to a non-
private method, array index out of bounds... Do not need
to be handled. Capturing them (try-catch) is optional.
 Checked exceptions. These represent invalid conditions in
areas outside the immediate control of the program (invalid
user input, database problems, network outages, absent
files). These exceptions have to be declared/propagated
(throws) or caught (try-catch). Example:
 Exceptions to be controlled while managing files.

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 13


3.3. Handling exceptions (VII)
 When a method produces/throws an exception that we do
not wish to capture, it has to be specified in the method’s
header. The reserved word throws is used. If we allow the
error to occur, then we will permit the exception to be
propagated up to the main method. Otherwise, if we wish
to catch it, the try-catch clause will be used. Example:
 When managing files that can produce IOException, if we
do not wish to catch the exceptions, we write:
public static void main (String [] args) throws
IOException{}

 If a method deals with different exception types, we do:


public static void main (String [] args) throws
Exception1, Exception2, …{}
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 14
3.3. Handling exceptions (VIII)
 Try-with resources
 Java 7 presented a new version of try blocks to handle
classes implementing the interface Closeable
 A Closeable object represents a resource (source or
destination) that can be closed.
◼ For example: a file or a database
 The syntax is:

try (resource opening) {


//It is not necessary to close the resource
} catch () { // optional
---several catch blocks can be found --
} finally { //optional
---
}
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 15
3.3. Handling exceptions (IX)
Example: Working with Scanner
try {
Scanner scan = new Scanner("datos.txt"); Before Java 7

while(scan.hasNextDouble()) {
System.out.println(scan.nextDouble());
Try with
} resources
} finally { //No necessary catch blocks
try {
scan.close();
} catch (IOException e){ try (Scanner scan = new
Scanner("datos.txt")) {
e.printStackTrace(); while(scan.hasNextDouble()) {
} System.out.println(scan.nextDouble());
}
} } //Not necessary to close the Scanner

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 16


3.3. Handling exceptions (X)
Example: Working with PrintWriter
try {
PrintWriter printer = new PrintWriter ("datos.txt");
printer.print("texto");
} catch (FileNotFoundException e) {
e.printStackTrace(); Try with
resources
} finally { Before Java 7
try {
printer.close();
} catch (IOException e) {
e.printStackTrace(); try (PrintWriter printer = new PrintWriter
} ("datos.txt")) {
} printer.print("texto");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 17
3.3. Handling exceptions (XI)
Example: Working with RandomAccessFile (explained later)
RandomAccessFile fich = null;
try {
fich = new RandomAccessFile("datos.txt", "rw");
fich.writeDouble(2.3);
Try with
} catch (IOException e) { resources
Before Java 7
e.printStackTrace();
} finally {
try {
fich.close(); try (RandomAccessFile fich = new
RandomAccessFile("datos.txt", "rw")) {
} catch (IOException e) {
fich.writeDouble(2.3);
e.printStackTrace();
} } catch (IOException e) {
e.printStackTrace();
} }

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 18


3.4. Creating new Exceptions (I)
 There are two kind of exceptions in JAVA:
 Exceptions defined by users.

 Exceptions predefined in the JAVA API.

 New exceptions can be created in JAVA. In order to define


an exception, we create a class that inherits from
Exception, the root class of the hierarchy of exceptions in
JAVA.

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 19


3.4. Creating new Exceptions (II)
 Sometimes, code is not included in the class because we
are only interested in the existence of the custom
exception. The constructor by default is used.
public class ExceptionName extends Exception{…}

 In the following example we also create the constructor,


but without code inside.
public class ExceptionName extends Exception{
public ExceptionName(String c){
}
}

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 20


3.4. Creating new Exceptions (III)
 In order to provide information about the error, a string can
be included in the constructor. As we can see, the
constructor in the superclass is called (by using super),
which prints a string passed as a parameter when the
exception is not caught. In the case of using the class
without a constructor, only the name ‘exception’ will be
printed.
public class ExceptionName extends Exception{
public ExceptionName(String c){
super(c);
}
}
 However, new custom exceptions will usually contain
attributes or methods that help to control errors.

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 21


3.4. Creating new Exceptions (IV)
 One advantage is that the system used to control
predefined exceptions is the same as that of custom
exceptions.
 However, this kind of exceptions must be thrown explicitly,
i.e., the programmer has to throw them by using the
following syntax:
throw new ExceptionName();
 Example. A class in which two constructors are overridden:
class NegativeIntegerException extends Exception{
public NegativeIntegerException(String message){
super(message);
}
public NegativeIntegerException(){
super(“Número negativo”);
}
}
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 22
3.4. Creating new Exceptions (V)
 To throw the custom exception manually, we could write
either:
if(n < 0) throw new NegativeIntegerException();
or
if(n < 0) throw new NegativeIntegerException(
“The number cannot be negative”);

 But if we do not wish to catch the exception inside the


method, we must use the following:

public double raiz2 (int n) throws NegativeIntegerException{


if(n < 0) throw new NegativeIntegerException();
return Math.sqrt(n);
}

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 23


3.4. Creating new Exceptions (VI)
 If we wish to catch the exception:
public double raiz2 (int n){
try{
if(n < 0) throw new NegativeIntegerException();
}
catch (NegativeIntegerException e){
n = -n;
}
finally{
return Math.sqrt(n);
}
}

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 24


3.5. JAVA exceptions hierarchy (I)
 Predefined exceptions are arranged through an exception
hierarchy in JAVA.

 The superclass of every error or exception is Throwable.


Two classes are derived from this one: Error and
Exception. All these classes are in the java.lang package.

 The Error class is a subclass of Throwable for errors that


cannot be recovered. Example:
 A programme that fails because of hardware.

 The Exception class covers every kind of problem that can


be caught. Every exception (predefined and custom)
comes from this class in JAVA.

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 25


3.5. JAVA exceptions hierarchy (II)
 Checked and unchecked exceptions also come from the
Exception class.

 Every unchecked exception comes from RuntimeException


which covers exceptions thrown by the JAVA Virtual
Machine during operation. These exceptions are thrown at
runtime, and the methods do not need to catch them (but
they could). Examples:
 ArrayIndexOutOfBoundsException

 ArithmeticException

 NumberFormatException

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 26


3.5. JAVA exceptions hierarchy (III)
 Other classes, which do not inherit from RuntimeException
but are children of the Exception class, do not depend on
the JAVA Virtual Machine. They are checked exceptions
that have to be caught or thrown. Example:
 IOException

 Custom exceptions which have been defined by us and


inherited from Exception are therefore checked, and if they
are not caught then they have to be declared. However,
exceptions, which inherit from RuntimeException and are
not caught, do not need to be declared to be unchecked.

 Some examples of this are shown in the following slides.

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 27


3.5. JAVA exceptions hierarchy (IV)

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 28


3.5. JAVA exceptions hierarchy (V)

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 29


3.5. JAVA exceptions hierarchy (VI)
 In the case of catching exceptions with try-catch clauses,
what will be the order of the catch statements?

 Catches for specific exceptions have to be placed first and


catches for general exceptions at the end.

 If exceptions are related by inheritance, we will place


catch statements for subclasses first.

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 30


3.5. JAVA exceptions hierarchy (VII)
 Let us consider the inheritance relationship between the
IOException class and the FileNotFoundException class in
JAVA.

 A program which manages the IOException and the


FileNotFoundException exceptions should be as follows:

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 31


3.5. JAVA exceptions hierarchy (VIII)

class Excepcion {
public static void main(String[] args) {
try {
BufferedReader entrada=
new BufferedReader(new FileReader(“datos”));
}
First, the specific one
catch(FileNotFoundException e) {
System.out.println("Fichero no encontrado");
}
Then, the general one
catch(IOException e) {
System.out.println("Error de Entrada/Salida");
}
}
}

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 32


3.5. JAVA exceptions hierarchy (IX)
 In the case of catching the IOException first, we will obtain
an error because the other catch statement will already
have been considered.

 When exceptions to catch are not remembered or are


unexpected, Exception is used. Since this is the
superclass, every exception is caught polymorphically. In
order to do this, the following catch is necessary:

catch (Exception e){


//code
}

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 33


3.5. JAVA exceptions hierarchy (X)
 The Throwable class contains predefined and custom
exceptions. Their most important methods are:
 getMessage(). A method that returns a string describing
the exception. The string is passed to the constructor as an
argument in custom exceptions. Otherwise, it is not
necessary to pass anything.

 toString(). A method inherited from Object and overridden


in this class. It returns the exception name and an error
description (provided by getMessage()).

 printStackTrace(). This returns the stack trace up to the


method call where the exception was thrown. The method
uses toString() to describe the error and includes the
methods that propagate this exception.
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 34
3.5. JAVA exceptions hierarchy (XI)
 What happens with exceptions when a method is
overridden?

 When a method declares (throws) one or more exceptions


and this method is overridden in a subclass, the subclass
method cannot throw more explicit exceptions ("checked"),
except those exceptions that are derived from these other
previously declared exceptions. Example:
 A method that declares IOException is overridden. The
overridden method may declare EOFException because it
is derived from the IOException.

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 35


3.6. Files and exceptions in Java (I)
 We are going to consider random access files and the
exceptions they thrown

 First of all, it is necessary to recall the types of files, the


class File and the text files.

 Classification of files:
 According to their organization
◼ Sequential (special record to indicate the end of the file: EOF)
◼ Random access
 According to their format
◼ Text files
◼ Binary files

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 36


3.6. Files and exceptions in Java (II)
 Class File;
 Auxiliary class, useful for working with files.

 This class does not work with streams like most of the
classes defined in java.io. It works directly with files and
the file system.
 An object File is used to obtain or modify information
associated with a file, such as permissions, time, date or
subdirectory, or to navigate the hierarchy or
subdirectories.
 This class is useful for retrieving information about a
specific file or subdirectory. An important utility of this
class is the capability to discover whether a file exists. The
File class allows us to check whether a file exists and then
decide whether to open the file or alert the user that the
content of the file could be removed.
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 37
3.6. Files and exceptions in Java (III)
 To use the File class, it is necessary to create an object
using the constructor:
File nameObject = new File (String name);
name should be the name of a file or subdirectory, including
the path on which it is located. By default, we shall be
working on the working directory.

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 38


3.6. Files and exceptions in Java (IV)
 Some methods in the class File
 exists(): Returns true if the file specified as argument in the
constructor of the class File is a file or subdirectory inside
the specified path. Otherwise, it returns false.
 getName(): Returns a String with the name of the file or
subdirectory.
 length(): Returns a long which indicates the length of the
file measured in bytes.
 delete(): Delete the file or subdirectory. It returns true if it
was deleted, and false if it was not possible to delete it.

 We shall now see how to write/read in a text file.

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 39


3.6.1. Sequential text files (I)
 Reading from a text file. Class Scanner in java.util
 Syntax:
Scanner entrada;
entrada= new Scanner (new FileReader(name)); o
entrada=new Scanner (name) ;
 Exceptions thrown by the constructor:
FileNotFoundException in java.io (“checked”)
 Methods
◼ close(): After using a file it must be closed
◼ useLocale (Locale.US)
◼ next () y nextLine() ; nextInt(), nextDouble(), nextFloat(),…
◼ hasNextInt (), hasNextDouble (), hasNextFloat (), ….
◼ Return true if the following element of the file can be read as an
integer, double, float, etc.

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 40


3.6.1. Sequential text files (II)
 Example for Reading from a file called texto.txt with several
records. Each record contains ID (int), surname (String)
and salary (double)
import java.io.*;
import java.util.Scanner;
class LecturaFichero {
public static void main(String [] args) {
String name= "texto.txt", apellido;
int id;
double salary;
boolean seguir = true;
Scanner entrada = null;
try {
entrada = new Scanner(new File(name));
//entrada = new Scanner(new FileReader(name));
}

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 41


3.6.1. Sequential text files (III)
catch (FileNotFoundException fnE) {
System.out.println(fnE.getMessage());
seguir = false;
}
if (seguir) {
while (entrada.hasNextInt()) {
id = entrada.nextInt();
apellido = entrada.next();
salary = entrada.nextDouble();
}
entrada.close();
} // End if
} // End main
} // End class

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 42


3.6.1. Sequential text files (IV)
 “Checked” exception : FileNotFoundException is thrown by
the constructor of the class Scanner, when an object of
class File or an object of class FileReader is passed .

 The method close() of the class Scanner and the methods


next() y hasNext() do not throw “checked” exceptions

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 43


3.6.1. Sequential text files (V)
 Writing with Class PrintWriter in java.io
 Syntax:
PrintWriter salida;
salida = new PrintWriter(nombre)
 To add inside the file without removing previous information
salida = new PrintWriter (new FileWriter (nombre, true))
◼ If the file does not exist then it is created, if it exists then it
removes its content unless it is open in addition mode using the
value true
 Exception thrown by the PrintWriter constructor :
FileNotFoundException in java.io (“checked”)
 Exception thrown by the FileWriter constructor:
IOException in java.io (“checked”)
 Writing methods: do not throw checked exceptions
println (); print (); printf ()
 Method close(): closes the file
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 44
3.6.1. Sequential text files (VI)
 Example of writing in a file called texto.txt . N records are
written. Each record contains ID (int), surname (String)
and salary (double)

import java.io.*;
import java.util.Scanner;
class EscrituraFichero {
public static void main(String [] args) {
Scanner teclado=new Scanner (System.in);
PrintWriter salida = null;
int n, id;
String surname;
double salary;
boolean seguir = true;

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 45


3.6.1. Sequential text files (VII)
try {
salida = new PrintWriter("texto.txt");
} catch (FileNotFoundException e) {
System.out.println("Error salida");
seguir = false;
}

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 46


3.6.1. Sequential text files (VIII)
if (seguir) {
System.out.println(“Number of data to be read: ");
n = teclado.nextInt();
for (int i = 0; i < n; i++) {
System.out.println(“Insert the surname");
surname = teclado.next();
System.out.println(“Insert salary");
salary = teclado.nextDouble();
salida.printf(" %d ", i + 1);
salida.printf("%s ", surname);
salida.printf(" %.2f", salary);
salida.println();
}
salida.close();
} // End if
} // End main
} // End class
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 47
3.6.1. Sequential text files (IX)
 FileNotFoundException: Checked exception throws by the
constructor. It is caught in this case.

 The methods close(), printf(), print() and println() of the


class PrintWriter do not throw checked exceptions.

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 48


3.6.2. Random Access Files (I)
 Read/Write within/from a random-access file. The
RandomAccessFile class is used, we do not have two
different classes for reading and writing

 When a RandomAccessFile stream is associated with a file,


the data are read or written from the current position
within the file

 All data are read or written as primitive data. For example,


upon writing an int value, 4 bytes are inserted into the file.
When reading a double value, 8 bytes are retrieved from
the file. The size of the data is fixed because Java keeps
the same size regardless of the environment (processor,
operative system).

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 49


3.6.2. Random Access Files (II)
 The RandomAccessFile class has two constructors:
◼ RandomAccessFile (File object_file, String mode)
◼ RandomAccessFile (String name, String mode)

 mode: “r” (read) y “rw”(read-write)


 Exceptions thrown by the constructor:
◼ FileNotFoundException

 In Java, a file is a sequence of bytes which ends with the


record EOF. There is an external pointer to let us know
where we are inside a file:
EOF

Pointer
Puntero
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 50
3.6.2. Random Access Files (III)
 Methods to know the position of the pointer:
 seek(long position): void
◼ Sets the file-pointer offset, measured from the beginning of
this file, at which the next read or write occurs
 getFilePointer(): long
◼ Returns the current offset in this file.
 skipBytes(int desplazamiento): int
◼ Attempts to skip over n bytes of input discarding the skipped
bytes. It returns actual number of bytes skipped.
 length(): long
◼ Returns the size of the file measured in bytes
 Exceptions thrown by these methods:
 IOException

 close() throws IOException


© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 51
3.6.2. Random Access Files (IV)
 Writing to a random-access file
 Create a file: Read and
◼ RandomAccessFile salida; write mode
◼ salida=new RandomAccessFile(name, “rw”);
 Use the method from DataOutputStream:
◼ writeInt (integer)
◼ writeDouble (double)
◼ writeBytes (text)
◼ writeUTF (String) Write a text following the fomat UTF
◼ 1 byte for each character + 2 bytes at the beginning.
◼ If we write n characters in UTF, n * 1 byte + 2 bytes will be
written into the file.
◼ Etc.
 Exceptions thrown by these methods:
◼ IOException
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 52
3.6.2. Random Access Files (V)
 Reading from random-access files
 Create a file: Read mode
◼ RandomAccessFile salida;
◼ salida=new RandomAccessFile(name, ”r”);
 Use the methods from DataInputStream:
◼ readInt()
◼ readDouble()
◼ readUTF()
◼ readFloat()
◼ readShort()
◼ etc.
 Exceptions thrown by these methods:
◼ EOFException
◼ IOException
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 53
3.6.2. Random Access Files (VI)
 It is important to know how to move the pointer within a
file. The most useful strategy is to skip records. In Java this
is possible if the size of the record is fixed. When the
length of the record is known, we can switch from records
to bytes or from bytes to records.
 Example:
 Suppose we want to store customers, which are
represented by their number (int), their name (String) with
30 characters and a salary (double).
 The size of the record, in bytes, is: int (4 bytes)+name (30*2
bytes)+double (8 bytes)= 44 bytes. This size can be
assigned to a variable: l_record = 44;

© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 54


3.6.2. Random Access Files (VII)
 More about the conversion from bytes to records:
◼ To convert data it is necessary to know whether the records
will be numbered by starting at zero or one.

0 1 2
 0-origen
0-origin

0 1 2 3 4 5 6 7 8 EOF

 1-origen
1-origin
1 2 3

◼ With 1-origin: position=(n-1)*l_record

◼ With 0-origin: position=n*l_record


© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 55

You might also like