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

Recordatorio de conceptos necesarios

 Las transparencias siguientes contienen un extracto del


Tema 3 del curso de Fundamentos de Programación II. Se
repasan aquí los ficheros en Java, tema de interés para el
curso de Estructuras de Datos:

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


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

 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 2


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 3
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 4


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 5


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 6


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 7


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();
System.out.println(id);
System.out.println(apellido);
System.out.println(salary);
}
entrada.close();
} // End if
} // End main
} // End class
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 8
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 9


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 10
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 11


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 12


3.6.1. Sequential text files (VIII)
if (seguir) {
System.out.println(“Number of data to be written: ");
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 13
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 14


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 15


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 16
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 the 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 17
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 format 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 18
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 19
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.

 Example:
 Suppose we want to store employees, which are
represented by their number (int), their name in UTF with
30 characters (30+2 bytes) 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;

 When the length of the record is known, we can switch


from records to bytes or from bytes to records.
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 20
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 21
3.6.2. Random Access Files (VIII)
 Example of reading from a random-access file called
datos.txt with several records. Each record contains as
data: ID (integer: 4 bytes long) surname (String: 30 + 2
characters long reading using UTF) and salary (double: 8
bytes long). Given the number of a record, it is read and
printed.
import java.io.*;
import java.util.Scanner;
class RandomLectura_2{
public static void main(String [] args) {
int long_Registro, n, id;
double y, salary;
String surname;
Scanner lectura = new Scanner (System.in);
RandomAccessFile entrada = null;
String nameFile = “datos.txt”;
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 22
3.6.2. Random Access Files (IX)
try {
entrada = new RandomAccessFile(nameFile, "r");
System.out.println(“Type the nº of record to read");
n = lectura.nextInt();
longRegistro=44; //4 bytes (int), 30(String)+2 UTF, 8(double)
entrada.seek((n - 1) * longRegistro);
id = entrada.readInt();
surname= entrada.readUTF();
salary = entrada.readDouble();
System.out.printf("%d %s %.2f\n", id, apellido, salary);
}
catch (EOFException e) {
System.out.println("\ End of the file. "
+ “The number of record does not exist.");
}
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 23
3.6.2. Random Access Files (X)
catch (FileNotFoundException e) {
System.out.println(“The file does not exist");
}
catch(IOException e) {
System.out.println(“Input/output exception:"+e.toString());
System.out.println(e.getMessage());
}
finally {
try {
entrada.close();
}
catch (IOException io) {
System.out.println(“File wrongly closed”+ io.toString());
System.out.println(io.getMessage());
}
}
}
}
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 24
3.6.2. Random Access Files (XI)
Example of writing within a random-access file called
datos.txt. n records are written. Each record contains ID (int),
surname (String) y Salary (double). The last two are read by
keyword.
// If the file exists, the information will be added at the end
import java.util.Scanner;
import java.io.*;
class RamdomEscritura {
public static void main(String [] args) {
int longApe = 30;
double salary;
int n, m;
RandomAccessFile salida = null;
Scanner teclado;
String nameFile, surname;
teclado = new Scanner (System.in);
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 25
3.6.2. Random Access Files (XII)
try {
salida = new RandomAccessFile("datos.txt", "rw");
System.out.println(“Type the number of records");
n = teclado.nextInt();
salida.seek(salida.length()); // End of the file
for (int i = 0; i < n; i++) {
salida.writeInt(i + 1); //Simulates the ID
System.out.println(“Type surname");
surname = teclado.next();
// adaptString() gives a fix length for each record
surname = adaptString(apellido, longApeTotal);
salida.writeUTF(surname);
System.out.println(“Type salary");
salary = teclado.nextDouble(); //Doesn’t throw IOExc.
salida.writeDouble(salary); //Throws IOException
} // End for } //End try
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 26
3.6.2. Random Access Files (XIII)
catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
finally {
try {
salida.close();
}
catch (IOException io ){
System.out.println(“File wrongly closed");
}
} // End finally
} // End main
--- Add here method adaptarCadena ----
} // End class
© Alfonso Niño (UCLM/FCCSS). Grado en Ingeniería Informática.Talavera de la Reina 27
3.6.2. Random Access Files (XIV)
/* It adds or removes characteres to/from a string in case its
lenght is lower or higher than longCadenaTotal. */
public static String adaptarCadena (String cadena,
int longCadenaTotal) {
int longCad = cadena.length();
if (longCad < longCadenaTotal) {
longCad = longCadenaTotal - longCad;
for (int j = 0; j < longCad; j++) {
cadena += " ";
}
}
else if (longCad >longCadenaTotal) { //Solución 1:
cadena = cadena.substring(0,longCadenaTotal);
}
return cadena;
}

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


3.6.2. Random Access Files (XV)
// Another possible solution
else if (longCad >longCadenaTotal) { //Solution 2:
String aux="";
for (int j = 0; j < longCadenaTotal; j++) {
aux += cadena.charAt(j);
}
cadena = aux;
}
return cadena;
}

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


3.6.2. Random Access Files (XVI)
 The file cannot be closed until the program has finished. If
salida.close() is put at the end of the first try, the method
write() throws an exception, the program won’t finish
because the control flow is addressed to the cacth block
with the exception e. Two options:
 The one of the previous program. A finally block at the end
of the try-catch and catch the exception in there
 Put inside the catch with the IOException, another try-
catch to close the file when the exception is thrown:

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


3.6.2. Random Access Files (XVII)
catch (IOException e ){
System.out.println(e.getMessage());
e.printStackTrace();
try {
salida.close();
}
catch (IOException io ){
System.out.println(“File wrongly closed")
}
}

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

You might also like