Class DirectAccessFile<T extends Serializable>
- All Implemented Interfaces:
Closeable,AutoCloseable
1. Què és DirectAccessFile?
DirectAccessFile<T> és una classe genèrica que permet guardar, llegir, inserir, actualitzar i esborrar objectes dins d’un fitxer binari utilitzant accés directe (RandomAccessFile).
Característiques principals: Permet guardar objectes de qualsevol classe sempre que implementin Serializable.
Els objectes es poden:
- Accedir per posició (accés directe).
- Recórrer seqüencialment.
Es poden fer:
- Insercions en qualsevol posició.
- Actualitzacions.
- Esborrats.
2. Requisits per als objectes
Qualsevol classe que es vulgui guardar ha d’implementar Serializable.
Exemple:
import java.io.Serializable;
public class Alumne implements Serializable {
private String nom;
private int edat;
public Alumne(String nom, int edat) {
this.nom = nom;
this.edat = edat;
}
@Override
public String toString() {
return nom + " (" + edat + ")";
}
}
3. Crear un fitxer d’accés directa
Amb nom de fitxer personalitzat: DirectAccessFile<Alumne> daf = new DirectAccessFile<>("alumnes.dat");
Amb nom per defecte (dades.dat): DirectAccessFile<Alumne> daf = new DirectAccessFile<>();
💡 Es recomana utilitzar try-with-resources perquè el fitxer es tanqui automàticament:
try (DirectAccessFile<Alumne> daf = new DirectAccessFile<>("alumnes.dat")) {
// treball amb el fitxer
}
4. Escriure objectes
Afegir un objecte al final del fitxer: daf.writeObject(new Alumne("Anna", 20));
Inserir un objecte en una posició concreta: daf.writeObject(new Alumne("Laura", 21), 1);
📌 Les posicions comencen a 0 Posició 0 → primer objecte Posició 1 → segon objecte Si la posició és més gran que la mida actual, l’objecte s’afegeix al final.
5. Llegir objectes
Llegir un objecte per posició: Alumne a = daf.readObject(0); System.out.println(a);
Llegir objectes seqüencialment daf.goToBeginning(); Alumne a; while ((a = daf.readObject()) != null) { System.out.println(a); }
6. Saber quants objectes hi ha int total = daf.size(); System.out.println("Nombre d'objectes: " + total);
7. Esborrar objectes
Esborrar un objecte per posició: Alumne eliminat = daf.deleteObject(1); System.out.println("Eliminat: " + eliminat);
L’objecte es retorna abans de ser esborrat (si existeix).
8. Actualitzar objectes
Alumne anterior = daf.updateObject(new Alumne("Marc", 23), 1); System.out.println("Abans de l'actualització: " + anterior);
📌 Internament: Es llegeix l’objecte antic. S’esborra. S’insereix el nou a la mateixa posició.
9. Esborrar tot el contingut del fitxer
daf.deleteAll();
El fitxer queda buit i el nombre d’objectes passa a ser 0.
10. Navegació pel fitxer
daf.goToBeginning(); // Anar a l'inici del fitxer daf.goToEnd(); // Anar al final del fitxer
Això és útil sobretot per a lectures seqüencials.
11. Resum de mètodes principals Mètode Funció writeObject(obj) Afegeix un objecte al final writeObject(obj, pos) Insereix un objecte a una posició readObject(pos) Llegeix un objecte per posició readObject() Llegeix seqüencialment deleteObject(pos) Esborra un objecte updateObject(obj, pos) Actualitza un objecte size() Nombre d’objectes deleteAll() Esborra tot el fitxer
12. Quan és útil aquesta classe?
Quan es vol treballar amb fitxers d’objectes sense usar bases de dades.
Quan cal accés directe per índex.
-
Constructor Summary
ConstructorsConstructorDescriptionCreates a direct access file with the default nameDirectAccessFile(String name) Creates a direct access file with the specified name -
Method Summary
Modifier and TypeMethodDescriptionvoidclose()Closes this resource, relinquishing any underlying resources.voidDeletes all content of the filedeleteObject(int position) Deletes the object at the specified position in the file and changes the position of the file pointer.getName()Shows the relative name of the fileintRetrieves the current position of the file pointer.voidMoves to the beginning of the filevoidgoToEnd()Moves to the end of the filevoidgoToPosition(int position) Moves to the indicated position of the file.Retrieves the instance at the current position of the file pointer and changes the position of the file pointer.readObject(int position) Retrieves the instance at the specified position in the file and changes the position of the file pointer.intsize()Returns the number of objects in the fileupdateObject(T object, int position) Updates the object at the specified position in the file and changes the position of the file pointer.voidwriteObject(T object) Writes a new object at the end of the file and changes the position of the file pointerbooleanwriteObject(T object, int position) Writes a new object at the specified position in the file and changes the position of the file pointer
-
Constructor Details
-
DirectAccessFile
Creates a direct access file with the specified name- Parameters:
name- the name given to the file- Throws:
IOException- if an error occurs with the file name that prevents its creation
-
DirectAccessFile
Creates a direct access file with the default name- Throws:
IOException- if an error occurs with the file name that prevents its creation
-
-
Method Details
-
getName
Shows the relative name of the file- Returns:
- the relative name of the file
-
getPosition
public int getPosition()Retrieves the current position of the file pointer.- Returns:
- the current position of the file pointer as an integer
-
writeObject
Writes a new object at the specified position in the file and changes the position of the file pointer- Parameters:
object- instance of class T to be saved in the fileposition- an integer value- Returns:
- true if the object was successfully written, false otherwise. The position must be greater than or equal to 0.
- Throws:
IOException- if an input/output error occurs
-
writeObject
Writes a new object at the end of the file and changes the position of the file pointer- Parameters:
object- instance of class T to be saved in the file- Throws:
IOException- if an input/output error occurs
-
readObject
Retrieves the instance at the specified position in the file and changes the position of the file pointer.- Parameters:
position- an integer value- Returns:
- the object read from the file, or null if the position is not greater than or equal to 0, or is nonexistent, or there are no objects
- Throws:
IOException- if an input/output error occursClassNotFoundException- if the class of the instance to be saved is not found
-
readObject
Retrieves the instance at the current position of the file pointer and changes the position of the file pointer.- Returns:
- the object read from the file, or null if the current position of the pointer is incorrect or there are no objects
- Throws:
IOException- if an input/output error occurs
-
deleteAll
Deletes all content of the file- Throws:
IOException- if an input/output error occurs
-
size
public int size()Returns the number of objects in the file- Returns:
- an integer indicating the number of objects in the file
-
goToBeginning
Moves to the beginning of the file- Throws:
IOException- if an input/output error occurs
-
goToEnd
Moves to the end of the file- Throws:
IOException- if an input/output error occurs
-
goToPosition
Moves to the indicated position of the file. If the position is lower than 0 the file pointer will be moved to the beginning of the file. If is greater than the number of objects in the file, the file pointer will be moved to its end. The next call toreadObject()method will return the object located at that position.- Parameters:
position- an integer value- Throws:
IOException- if an input/output error occurs
-
deleteObject
Deletes the object at the specified position in the file and changes the position of the file pointer.- Parameters:
position- an integer value- Returns:
- the deleted object if found, null otherwise. The position must be greater than or equal to 0 and less than the number of objects in the file.
- Throws:
IOException- if an input/output error occursClassNotFoundException- if the class of the instance to be deleted is not found
-
updateObject
Updates the object at the specified position in the file and changes the position of the file pointer.- Parameters:
object- the new props of the updated objectposition- an integer value- Returns:
- the updated object before update if found, null otherwise. The position must be greater than or equal to 0 and less than the number of objects in the file.
- Throws:
IOException- if an input/output error occursClassNotFoundException- if the class of the instance to be updated is not found
-
close
Closes this resource, relinquishing any underlying resources. This method is invoked automatically on objects managed by thetry-with-resources statement.While this interface method is declared to throw
Exception, implementers are strongly encouraged to declare concrete implementations of theclosemethod to throw more specific exceptions, or to throw no exception at all if the close operation cannot fail.Cases where the close operation may fail require careful attention by implementers. It is strongly advised to relinquish the underlying resources and to internally mark the resource as closed, prior to throwing the exception. The
closemethod is unlikely to be invoked more than once and so this ensures that the resources are released in a timely manner. Furthermore it reduces problems that could arise when the resource wraps, or is wrapped, by another resource.Implementers of this interface are also strongly advised to not have the
closemethod throwInterruptedException.This exception interacts with a thread's interrupted status, and runtime misbehavior is likely to occur if an
InterruptedExceptionis suppressed.More generally, if it would cause problems for an exception to be suppressed, the
AutoCloseable.closemethod should not throw it.Note that unlike the
closemethod ofCloseable, thisclosemethod is not required to be idempotent. In other words, calling thisclosemethod more than once may have some visible side effect, unlikeCloseable.closewhich is required to have no effect if called more than once.However, implementers of this interface are strongly encouraged to make their
closemethods idempotent.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Throws:
IOException- if this resource cannot be closed
-