0% found this document useful (0 votes)
68 views9 pages

Sheet 09 - Files: Programação Orientada A Objectos

1. Files allow storing data persistently on disk. The File class represents file paths and allows manipulating files. 2. The FileWriter class creates a link between a file and application to write data to the file. The PrintWriter class builds on FileWriter and provides convenient methods for writing strings and lines of text to files. 3. The FileReader class creates a link for reading from a file. The BufferedReader class builds on this and allows reading lines of text from a file using its readLine() method.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views9 pages

Sheet 09 - Files: Programação Orientada A Objectos

1. Files allow storing data persistently on disk. The File class represents file paths and allows manipulating files. 2. The FileWriter class creates a link between a file and application to write data to the file. The PrintWriter class builds on FileWriter and provides convenient methods for writing strings and lines of text to files. 3. The FileReader class creates a link for reading from a file. The BufferedReader class builds on this and allows reading lines of text from a file using its readLine() method.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Programao

Orientada a Objectos

SHEET 09 FILES
Files are the mechanism that allows you to store data persistently to disk.

1. The File class


Any file to be used must be identified unequivocally. File class objects allow representing the name of a file in Java, independently of the OS used. The File class belongs to the java.io package, and you can create an object of type File, giving its constructor a string with the filename:
import java.io.*; () File f1; f1 = new File("shopList");

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!

Some methods of the File class:

Programao Orientada a Objectos

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.

2. Writing Text files


Writing in a file implies somehow to create a link between our application and the file. This link will allow transferring information between one and another. These connections or "pipes" are sometimes called streams.

The FileWriter class


The FileWriter class, belonging to the java.io package, allows you to create a link between a file and an application, i.e. it allows information exchange between the application and the file. You can create an instance of FileWriter at the expense of a File object. The attempt to create an object of type FileWriter can give rise to an exception of type IOException if the file is impossible to open or create. This exception must be caught or declared by the method where the object is being created.
import java.io.*; () try { File f = new File("result.out"); FileWriter fs = new FileWriter(f);

() } catch (IOException e) { } System.out.println( "An exception occurred " + e + " when creating the FileWriter fs");

Programao Orientada a Objectos

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:

Programao Orientada a Objectos

PrintWriter ps = new PrintWriter(new FileWriter(new File("fich.txt")));

3. Reading Text files


In a manner analogous to writing data in files, it is also possible to obtain data from a file. Reading a text file departs from a FileReader (obtained from a File) which models an input stream. If you try to create a FileReader from a non-existent file, a FileNotFoudException is launched. Then this FileReader is used to create an InputStreamReader that models a link between the data source and the application. Although working with characters (instead of bytes), it does not recognize line breaks. So you should use a BufferedReader instead. This class provides the readLine method that allows us to read the input line by line. The following code opens the file "fich.txt" for reading, reads the first two lines and displays them on the monitor.
try { } File f = new File("fich.txt"); FileReader fis = new FileReader(f); BufferedReader br = new BufferedReader(isr); String s = br.readLine(); System.out.println("1: " + s); s = br.readLine(); System.out.println("2: " + s); System.out.println("File fich.txt does not exist"); System.out.println("Exception when reading a line from the file");

} catch (FileNotFoundException e) { } catch (IOException e) {

Programao Orientada a Objectos

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

Now you can create objects to manipulate the object files:


ObjectInputStream ois = new ObjectInputStream(is); ObjectOutputStream oos = new ObjectOutputStream(os);

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.

Programao Orientada a Objectos

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

6. The ObjectFile class


It can be developed a class that simplifies the use of object files that includes methods to open a file, write an object in a file, read an object from a file and close a file. Similarly a class can be developed for text files. The class will have attributes such as references to an object of the class ObjectInputStream and to an object of the class ObjectOutputStream:
import java.io.*; public class ObjectFile {

Programao Orientada a Objectos

private ObjectInputStream iS; private ObjectOutputStream oS;

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));

public void openForWriting(String nameOfFile) throws IOException { } oS = new ObjectOutputStream(new FileOutputStream(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);

Programao Orientada a Objectos

The methods to close the files are limited to using the close () method of the ObjectInputStream and ObjectOutputStream classes:

public void closeReading() throws IOException { } iS.close();

public void closeWriting() throws IOException { } oS.close();

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.

Programao Orientada a Objectos

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.

You might also like