PROGRAMACIÓN PARA SISTEMAS
DE TELECOMUNICACIÓN
Chapter 3
Exceptions and Files
FILES
Files in Java
l
l
l
Needed for accessing huge amount of data.
A file is a collection of structured data that is
managed in an integrated way.
Files are organised into basic structures called
registers. These registers are organized into
fields.
Identification number (key); name; address;
telephone; category; salary
Type of files
l
Depending of the access type:
l
l
Sequential access: the registers are
obtained sequentially. This type of access
can be implemented both in sequential and
direct access storage devices.
Direct access: Any register can be
accessed since all are addressable. This
type of access requires a direct access
storage device.
Type of files
l
Considering the underlying hardware:
l
l
Sequential devices: to access the register n
we need first to access the previous n-1
registers.
Direct access devices: any position is
addressable.
l
We need a key field to calculate the
position.
Type of files
l
Considering the organization of data:
l
Sequential organization: It implies sequential
access. Registers are recorded consecutively. The
order when writing is the order when reading.
Special EOF mark.
l
Direct (random) organization: The physical
order does not correspond with the logical one. The
direct access to a given position is calculated using
the position of records in the file (relative place)
using the key. This organization requirest direct
access.
Type of files
l
Considering the type of organization:
l
Indexed-Sequential: Data is stored in two files:
one for content (direct access) and another for
indexes (sequentially accessed).
The file of index has many entries as areas in the
register file.
In each entry of the index file is stored the address
the last record in the corresponding area.
Type of files
l
Example of indexed-sequential organization:
Bartolo
1
Juan
4
Pedro
7
First we look for the value in
the index file: if we want to
find Luis, after finding to
Pedro we detect an
alphabetic jump. We obtain
the position 7 from where we
start the sequential reading
for the area.
1
Amparo
2
Ana
3
Bartolo
4
Esther
5
Eva
6
Juan
7
Lola
8
Lourdes
9
Luis
10
Pedro
Area 1
Area 2
Area 3
Type of files
l
Considering the format:
l
l
l
Binary files: the content are bits. We can
not read the file with a text editor.
Text files: the content are sequences of
characters following a standard (Unicode).
The file is readable.
Comparative of advantages and
drawbacks.
Operations on Files
l
Creation, opening, query, modification,
insertion, deletion, movement of the
pointer, and closing.
Java files
l
In Java, all the inputs/outputs are managed
as streams.
l
java.io
l
When a file is opened an object is created
Very important exception handling!
and a stream is associated.
Java files
Java views each file as a sequential stream of bytes, each file ends with
either an end-of-file marker or at a specific byte number record.
Three streams are automatically created when we begin executing a
Java program:
² System.in - standard input stream object (normally the keyboard or
mouse)
² System.out - standard output stream object (normally the display)
² System.err - standard error stream object (normally the display)
Sequential files in Java
l
The concept of register does not exist in Java. The
programmer has to define the structure of the file.
l
The basic streams manage 8 bits in every basic
operation.
l
With the internacionalization of Unicode (Readers
and Writers) the size is 16 bits.
Binary Sequential files in Java
l
Two ways of working with these files:
l
Byte to byte.
l
Data converted to bytes.
Binary Sequential files in Java: byte
to byte
l
FileOutputStream and FileInputStream.
l
Writing:
l
When opened the file for writing the data is truncated. If
the file does not exist it is created.
FileOutputStream output;
output= new FileOutputStream(name);
FileOutputStream(File Objeto_file);
FileOutputStream(String file_name, boolean add);
Binary Sequential files in Java: byte
to byte
import java.io.*;
class Files{
public static void main(String [] args) {
FileOutputStream output; //Declaring the
reference to the stream
try
{
// Creating the file
output=new FileOutputStream(args[0]);
/* If no error yet, many integers are written to
disc*/
for (int i=0;i<99;i++)
{
output.write(i);
}
output.close();
} // End of try
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(”Enter the file name!");
}
catch(IOException e)
{
System.out.println("Excepcion de E/S: "
+e.toString());
}
} // end of main
} // en of class
Binary Sequential files in Java: byte
to byte
l
Reading: FileInputStream.
FileInputStream input;
input= new FileInputStream(name);
FileInputStream(File Objeto_file);
// it can throws FileNotFoundException
read gives a byte per reading and returns it as an integer.
End of file is -1
Binary Sequential files in Java: byte
to byte
import java.io.*;
class Files{
public static void main(String [] args) {
int i;
boolean follow=true;
FileInputStream input;
FileOutputStream output;
try {
// Creating the files
input=new FileInputStream(args[0]);
output=new FileOutputStream(args[1]);
/* if no error, we write integers to disc*/
do {
i=input.read();
follow=(i!=-1);
if (follow) {
salida.write(i);
System.out.println(i); // Visualizing the data
}
} while (follow);
input.close();
output.close();
} // End of try
catch(ArrayIndexOutOfBoundsException e) {
System.out.println(”Enter the names of
source and target files");
}
catch(FileNotFoundException e) {
System.out.println(”File does not exist");
}
catch(IOException e) {
System.out.println(”I/O Exception:
"+e.toString());
}
} // End of main
} // End of class
Binary Sequential files in Java: data
to bytes
l
Writing: DataOutputStream.
DataOutputStream output;
output = new DataOutputStream (new FileOutputStream(…));
// The existing data will be deleted. See in help how to avoid it when
needed.
DataOutputStream output = new DataOutputStream (new
(BufferedOutputStream (new FileOutputStream(name)));
writeInt(integer_var);
writeUTF(string_var);
writeDouble(double_var);
writeFloat
writeChar
WriteLong, etc.
Binary Sequential files in Java: data
to bytes
import java.io.*;
class Files{
public static void main(String [] args) {
double value;
boolean follow=true;
DataOutputStream output;
BufferedReader keyboard;
try {
keyboard=new BufferedReader(new
InputStreamReader(System.in));
System.out.println(”Enter the file name:");
output=new DataOutputStream(new
BufferedOutputStream (new
FileOutputStream(keyboard.readLine())));
while (follow) {
System.out.println();
System.out.println(”Enter a real number:");
value=Double.parseDouble(keyboard.readLine());
output.writeDouble(value);
System.out.println();
System.out.println(”Do you want to continue. Y:0
N:1");
value=Double.parseDouble(keyboard.readLine());
if (value==1) {follow=false;}
} // End while
output.close();
}
catch(IOException e) {
System.out.println(”I/O Exception: "+e.toString());
}
} // End of main
} // End of class
Binary Sequential files in Java: data
to bytes
l
Reading: DataInputStream.
DataInputStream input;
input= new DataInputStream (new (BufferedInputStream (new
FileInputStream(nombre)));
readChar()
readDouble()
readInt()
readFloat()
readLine()
readUTF()
readBoolean()
readByte()
readShort()
readLong()
All them can throw an
IOException (checked)
EOF detected with a
EndOfFileException
Binary Sequential files in Java: data
to bytes
Thanks to the buffer we have readLine
because InputStreamReader offers
reading one char per time
import java.io.*;
class Files {
public static void main(String [] args) {
double value; boolean follow=true;
DataInputStream input=null;
BufferedReader keyboard;
try {
try {keyboard=new BufferedReader(new
InputStreamReader(System.in));
System.out.println(”Enter the source file name:");
input=new DataInputStream(new
BufferedInputStream (new
FileInputStream(keyboard.readLine())));
}
catch(FileNotFoundException e) {
System.out.println(”Non valid file name");
follow=false; // For not entering the following ‘if’
} // end of second try-catch
// If FileNotFoundException we follow
if (follow) {
while (follow) {
try {
// try within the ‘while’
value=input.readDouble();
System.out.println(value);
}
catch(EOFException e) {
System.out.println(”Reached EOF");
follow=false; // To finish the loop
} // End of del try-catch within the loop
} // end of loop
input.close(); // Closing the file
} // end of ‘if’
} // finish outer try
catch(IOException e) {
System.out.println(”I/O Exception"+
e.toString());
} // this catch is from the outer try
} // end of main
} // end of class
Text Sequential files in Java
l
Writing:
l
We can use PrintWriter that contains methods as
println and print with the same behaviour as
System.out.
Printwriter output;
output = new PrintWriter(new FileWriter(name));
Text Sequential files in Java
import java.io.*;
class Files {
public static void main(String [] args){
PrintWriter output=null; //Initializing references
BufferedReader input=null;
String file="";
String line=null;
try {
file=args[0];
input= new BufferedReader
(new InputStreamReader(System.in));
output= new PrintWriter
(new FileWriter(file));
System.out.println(”Enter three lines of text:");
for (int cont=1;cont<4; cont++) {
line=input.readLine();
output.println(cont+" "+line);
}
input.close();
output.close();
System.out.println(”These lines have been wrotten
in “+fichero);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println(“You must enter the file name!");
}
catch(IOException e){
System.out.println(”File could not be opened\n"
+e.toString());
}
} //end main
} //end class
Text Sequential files in Java
l
Reading:
l
l
We can use BufferReader to read a textfile using
readLine(). Also, the method read() is
available to read a single character.
readLine() returns null when EOF, but read()
reutns -1. They do not throw EOFException
BufferReader entrada;
entrada = new BufferReader(new FileReader(nombre));
Text Sequential files in Java
import java.io.*;
class Files {
public static void main(String [] args) {
String file1="", file2="";
BufferedReader input=null;
PrintWriter output=null;
try {
try {
file1=args[0];
file2=args[1];
input= new BufferedReader
(new FileReader(file1));
output= new PrintWriter
(new FileOutputStream(file2));
int cont=0;
String line=input.readLine();
while(line!=null) {
// Reading until EOF
cont++;
output.println(cont+" "+line);
line=input.readLine();
}
System.out.println(cont +" lines written to"
+file2);
} // end of inner try
catch(ArrayIndexOutOfBoundsException e) {
System.out.println(”Enter the source and target file
names!");
}
catch(FileNotFoundException e) {
System.out.println(”File "+fichero1+" not found");
}
finally {
input.close();
output.close();
}
} // End of outer try
catch(IOException e){
System.out.println(”the file could not be
opened\n”+e.toString());
}
} //end main
} //end class
From text to bin
Random Access Files in Java
l
l
l
l
Previous examples were with sequential access.
When we need a fast access to huge amount of
data we need an alternative.
With random access we can modify or delete part of
the data without affecting the rest of the file.
Again, the programmer needs to define the
structure of the data in the file.
Random Access Files in Java
l
Creation of files:
l
l
l
RandomAccessFile i the Java class to both read and write in
random access files. It has an special EOF mark.
Reading/writing is made considering the position where the pointer
is pointing. We can freely move such pointer to any point in data
(beginning, end, middle, position x,…).
All data are read/written as primitive data types (int 4 bytes, double
8 bytes,...).
RandomAccessFile(File object, String mode)
RandomAccessFile(String name, String mode)
mode:
"r"
"rw"
Random Access Files in Java
l
Methods of RandomAccessFile:
l
void seek(long): Sets the file-pointer offset, measured
from the beginning of this file, at which the next read or
write occurs.
l
long getFilePointer(): Returns the current offset in
this file.
l
int skipBytes(int n): Attempts to skip over n bytes of
input discarding the skipped bytes.
l
long length(): returns the lenght of this file.
Random Access Files in Java
l
Writing:
RandomAccessFile output;
output = new RandomAccessFile(name, "rw");
l
writeInt(int): writes an int.
l
writeDouble(double): writes a double.
l
writeBytes(String): writes a string as a byte
sequence.
l
uses 8 bits and add 2 more at the
beginning to indicate the size of the string.
writeUTF(String):
Random Access Files in Java
import java.io.*;
class Files {
public static void main(String [] args) {
double value;
int cont=0;
boolean follow=true;
RandomAccessFile output;
BufferedReader keyboard;
try {
teclado=new BufferedReader(new
InputStreamReader(System.in));
System.out.println(”Enter file name:");
salida=new
RandomAccessFile(keyboard.readLine(), "rw");
salida.seek(salida.length()); /* skip to the end of
file */
while (follow) {
cont++;
System.out.println();
System.out.println(”Enter a real value:");
value=Double.parseDouble(keyboard.readLine()
);
salida.writeInt(cont);
salida.writeDouble(value);
System.out.println();
System.out.println(”Do you want to continue. Y:0 N:1");
value=Double.parseDouble(keyboard.readLine());
if (value==1) follow=false;
} // End while
output.close();
}
catch(IOException e) {
System.out.println(”I/O Exception: “+ e.toString());
}
} // end main
} // end Files
Random Access Files in Java
l
Reading:
RandomAccessFile input;
input= new RandomAccessFile(name, "r");
l
readInt(): reads an integer.
l
readDouble(): reads a double.
l
readBytes(): reads a string as a byte sequence.
l
readUTF(): reads the string in UTF format (a byte per
character).
l
readFloat(), readShort(), ...
Random Access Files in Java
l
How to move in file:
l
l
We need to know the size of each register.
For instance, if the register includes an integer
(int), a string of 30 chars and a real number
(double), the size in bytes is:
4 (int) + 30+2 (string) + 8 (double)
Random Access Files in Java
import java.io.*;
class Files {
public static void main(String [] args) {
double value;
int n, l_register, intNumber;
boolean follow=true;
RandomAccessFile input;
BufferedReader keyboard;
l_register=12; // 4 bytes (int)+ 8 bytes (double)
try {
keyboard=new BufferedReader(new
InputStreamReader(System.in));
System.out.println(”enter file name:");
input=new
RandomAccessFile(keyboard.readLine(), "r");
while (follow) {
System.out.println();
System.out.println(”Enter register number:");
n=Integer.parseInt(keyboard.readLine());
input.seek((n-1)*l_register);
intNumber=input.readInt();
value=input.readDouble();
System.out.println();
System.out.println("Register: ”+intNumber+" "+value);
System.out.println();
System.out.println(”Do you want to continue?. Y:0
N:1");
value=Double.parseDouble(keyboard.readLine());
if (value==1) follow=false;
} // end while
input.close();
}
catch(IOException e) {
System.out.println(”I/O Exception”
+e.toString);
}
} // end main
} // end Files
The class File of Java
l
l
l
l
File works directly with files and file systems.
File does not open a file neither it offers utilities for
processing files.
File is used to obtain/modify data from a file: permissions,
hour, time, subdirectory,…
For instance, if we open a file with FileOutputStream and
the file already exists, then the entire content is deleted. So,
we could use File to check whether the file exists.
The class File of Java
l
Methods of File:
l
File(String name)
l
File(String directory, String name)
l
File(File directory, String name)
l
File file = new File("data.dat");
l
exists(): returns true if the descriptor corresponds to a file or directory.
l
getName(): returns as a String the file/directory name
l
length(): returns as a long number the length of the file
l
lastModified(): returns as a long value the time the file was modofied.
l
list(): returns a list of String objects with the content of the directory.
Files and Objects in Java
l
l
l
Java gives the chance to serialize objects in order to store
them in file as byte sequences.
It allows recovering previous execution states.
For allowing that serialization, the class must implement the
predefined Java Serializable interface:
Class Example implements Serializable{...}
l
From there, we can write and read objects using:
ObjectOutputStream y ObjectInputStream.
Files and Objects in Java
l
For instance, for creating the output stream:
ObjectOutputStream output;
output= new ObjectOutputStream( new FileOutputStream(name));
l
The input stream :
ObjectInputStream input;
input= new ObjectInputStream(new FileInputStream(name));
l
Operations over the streams:
writeObject(object);
readObject();
Files and Objects in Java
l
So:
ObjectOutputStream output;
output= new ObjectOutputStream(new
FileOutputStream("data.dat"));
output.writeObject(obj1);
l
And afterwards:
ObjectInputStream input;
input= new ObjectInputStream(new
FileInputStream("data.dat"));
obj2 = (Example) input.readObject();
Caution!: ClassCastException
Summary table
Byte Based
Character Based
Input
Output
Input
Output
Basic
InputStream
OutputStream
Reader
InputStreamReader
Writer
OutputStreamWriter
Arrays
ByteArrayInputStream
ByteArrayOutputStream
CharArrayReader
CharArrayWriter
Files
FileInputStream
RandomAccessFile
FileOutputStream
RandomAccessFile
FileReader
FileWriter
Pipes
PipedInputStream
PipedOutputStream
PipedReader
PipedWriter
Buffering
BufferedInputStream
BufferedOutputStream
BufferedReader
BufferedWriter
Filtering
FilterInputStream
FilterOutputStream
FilterReader
FilterWriter
Parsing
PushbackInputStream
StreamTokenizer
PushbackReader
LineNumberReader
Strings
Data
StringReader
DataInputStream
Data - Formatted
Objects
Utilities
DataOutputStream
PrintStream
ObjectInputStream
SequenceInputStream
StringWriter
ObjectOutputStream
PrintWriter
0
Puede agregar este documento a su colección de estudio (s)
Iniciar sesión Disponible sólo para usuarios autorizadosPuede agregar este documento a su lista guardada
Iniciar sesión Disponible sólo para usuarios autorizados(Para quejas, use otra forma )