Sheet 09 - Files: Programação Orientada A Objectos
Sheet 09 - Files: Programação Orientada A Objectos
Orientada a Objectos
SHEET 09 FILES
Files are the mechanism that allows you to store data persistently to disk.
The file does not have to exist nor does it come into existence only because you have created the object of type File. The only thing created is a representation (for Java) of a name, for a hypothetical file (or directory). However, if the file exists the object File created actually refers to it. For example, we can delete a file or change its name as follows:
File
one
=
new
File("temporary");
File
another
=
new
File("garbage");
one.renameTo(another);
//Temporary
pass
to
be
called
garbage
another.delete();
//Garbage
is
deleted!
public boolean renameTo(File dest) throws SecurityException public boolean delete() throws SecurityException
Renames the file (or directory) in question to "dest". Deletes the file (or directory) in question. If it is a directory it must be empty.
() } catch (IOException e) { } System.out.println( "An exception occurred " + e + " when creating the FileWriter fs");
In the example above, there will be a link between the application and a file of name "result.out." Even if the file does not exist initially, a new file is created with that name and the connection is established. However the connection obtained at the expense of FileWriter works with the information in bytes which becomes somewhat inconvenient (e.g. does not recognize text formatting: line breaks, tabs, etc.). In other words, this class provides us with a link to a file, but does not provide convenient methods to send the information we want. The PrintWriter class Instances of PrintWriter class, also belonging to the java.io package, have methods that recognize lines and strings. To write conveniently in a file, you must convert the instance of the FileWriter class, (which makes the link to the file), in an instance of the PrintWriter class (which has the methods that we need). The conversion can be carried out as follows:
import
java.io.*;
()
try
{
}
File
f
=
new
File("fich.txt");
FileWriter
fs
=
new
FileWriter(f);
ps.println("line1
!!!");
ps.println("line2
!!!");
ps.close();
System.out.println(
"
An
exception
occurred
"
+
e
+
"
when
creating
the
FileWriter
fs");
PrintWriter
ps
=
new
PrintWriter(fs);
} catch (IOException e) {
In the above example we create a new file (or open it, if it exists), to write two lines and we close it. If the file already exists its contents would be replaced by the two lines in question. Typically, instances of File and FileWriter classes are just used to create the PrintWriter so that the variables are not necessary and may shorten to:
4. Object files
Analogous to writing / reading text we also can read / write objects from files, but in these cases it should be used the FileInputStream and FileOutputStream classes to establish the corresponding data flows:
FileInputStream
is
=
new
FileInputStream(new
File(nameOfFile));
FileOutputStream
os
=
new
FileOutputStream(new
File(nameOfFile));
Or, shortly:
FileInputStream
is
=
new
FileInputStream(nameOfFile);
FileOutputStream
os
=
new
FileOutputStream(nameOfFile);
To store user-defined class objects in files, you have to add in the header of these classes the words implements Serializable:
public
class
Group
implements
Serializable
5. Exceptions
An exception is something that occurs during the execution of a method that prevents it from working according to the planned. Its detection and treatment allows handling these situations in a controlled manner. The methods that use input and output operations, have to deal with exceptions (try catch statement) or declare their propagation at the expense of the throws clause.
For example the method openForReading (), which opens a file for reading, detects the absence of the file:
public boolean openForReading(String nameOfFile) { } try { } iS = new ObjectInputStream(new FileInputStream(nameOfFile)); return true; return false;
} catch (IOException e) {
The method attempts to execute the instructions included in the try block. If an error is not generated, the execution continues at the statement following the catch block. In the event of an error (exception), the catch blocks are checked, searching for one that applies to the type of exception that has emerged. In the method openForReading (), the exception created (FileNotFoundException because the file does not exist) is of type IOException, which falls into the catch. Thus, the catch instruction is executed, the method ends and returns false to indicate that it cannot open the file
The methods for opening the file for reading and writing can be:
public
void
openForReading(String
nameOfFile)
throws
IOException
{
}
iS
=
new
ObjectInputStream(new
FileInputStream(nameOfFile));
Reading an object from a file can be made by the method readObject () of the class ObjectInputStream:
public
Object
readObject()
throws
IOException,
ClassNotFoundException
{
}
return
iS.readObject();
Once it is intended that the method can read any type of object, you cannot use the name of any particular class, but it will be the calling method that will specify, through a cast, which class this object must belong to. The method may propagate an error of the type ClassNotFoundException that is generated if the file does not contain any object. Writing an object in a file can be obtained with the method:
public
void
writeObject(Object
o)
throws
IOException
{
oS.writeObject(o);
The methods to close the files are limited to using the close () method of the ObjectInputStream and ObjectOutputStream classes:
Exercises 1. Copy
Write a program that makes a copy of a text file, changing the extension to "bkp". The name of the file to copy should be entered by the user.
2. Temperatures
Create a program that asks the user for the name of a text file containing the minimum and maximum temperatures for a particular city over a month. Write a program that reads the file and determines the highest observed temperature range (difference between the maximum and the minimum for a particular day). The program should also indicate what the day of the month was where it occurred.
3. Permutations
Create a program that asks the user the name of a file. This file should contain two lines: the first line should contain a four-letter word, and the second a word up to eight letters.
Use the first line to make permutations with the letters of the word, and use the second as the file name where you will save these permutations. The original word and the permutations must also be shown on the monitor.
4. Contact management
In the problem of the previous class on a contact management system make the necessary changes so that: on entering all the information is loaded from file (s) of objects and on leaving all the information is stored in file (s) of objects.
5. American test
The answers to a test of American type, containing 20 multiple choice questions are stored in a file of suitable objects. Each answer may take the value 1, 2, 3, 4 or 5, corresponding to the selected option, and if it has not been answered, the value 0. Create a program that reads one of these files and determines for a class (30 students) the grade obtained by each one - the key with the correct answers is provided through another file consisting of integers. A correct answer is graded 1 point, a wrong answer deducts 0.5 points and a blank answer has no influence on the final result.