Professional Documents
Culture Documents
Ficheros
Ficheros
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
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.
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;
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
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;
0 1 2
0-origen
0-origin
0 1 2 3 4 5 6 7 8 EOF
1-origen
1-origin
1 2 3