Data Files

advertisement
Java the UML Way
http://www.tisip.no/JavaTheUmlWay/
Using Data Files and Streams
What is a data file?
Data files and streams
Example: Writing and reading a file
Sequential data files – summary
In-/out-classes in Java
Reading numbers from a file
Communication with the console
The process of writing to / reading from a file
Random access to the contents of a file
Saving objects to a file / serialization
The instanceof operator
Summary – data files
versjon 2002-04-17
page 2
page 3
page 4-7
page 8-9
page 10-11
page 12
page 13
page 14-15
page 16-17
page 18-21
page 22
page 23
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11
What is a Data File?
• Up to now our programs have communicated with the world through
the keyboard and the screen.
• Programs can also communicate with data files.
• All the files you work with in word processors, spreadsheet programs,
and editors are data files.
• Data files make it possible for the program to remember data from run
to run. This is practical for us as users—we don't need to reenter data if
we run a program several times with only minor changes in the input
data.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 2
Data Files and Streams
•
We can think of the data that is sent between a program and a file as a stream.
The data streams from a source to a destination.
– We start by opening the stream.
– We fill it up with data (“write” to the stream) if the stream is running from the
program to the file.
– If the stream is running in the opposite direction, the program empties the stream of
data as the data is “read.”
– Finally, we close the stream.
•
•
•
•
In the program, we start by attaching a stream object to the file we want to
read from or write to. We say that we are opening the file.
This stream is the object we are working with in the program. We send read
and write messages to the stream object.
When we finally close the stream object, this leads to the termination of the
connection to the physical data file. We say that we are closing the file.
There are many classes that make stream objects. We make the stream objects
in a somewhat special way:
– an instance of one stream class will preferably become an argument for the
constructor for another stream class. We can continue with this in several steps
before we get a stream we are satisfied with.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 3
A Program Communicates with a Data File
Tony Kingsley
Ken Brown
Margaret Gibson
the program
reads data
from the
data file
the program
runs
the program
writes data
to the data
file
nameFile.txt
before the
program runs
Tony Kingsley
Ken Brown
Margaret Gibson
Matthew Johnson
Peter Adams
nameFile.txt
after the program
has run
the program reads
data from the keyboard
the user enters data
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 4
Reading All the Names from the File
String filename =
"nameFile.txt";
opens the
file
data should
be buffered
reads one line at
a time, prints it
to the screen
closes the stream,
and with that the file
FileReader readConnToFile = new
FileReader(filename);
BufferedReader reader = new
BufferedReader(readConnToFile);
String result = "The register:\n";
String oneName = reader.readLine();
while(oneName != null) { // null means end-of-file
result += oneName + "\n";
oneName = reader.readLine();
}
JOptionPane.showMessageDialog(null, result);
reader.close();
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 5
Reading from File via Streams
reader:
readConnToFile:
client
“client”
BufferedReader
InputStreamReader
sends
the message
readLine()
readLine()
[buffer empty]
to reader
inFile:
FileInputStream
fill()
if empty buffer,
reader has to
fill the buffer
read()
read()
readConnToFile
reads bytes
and converts
them into char.
The result is
put in the buffer.
reader fetches
one line from
the buffer and
returns it
to the client
many
Unicode
characters
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
many bytes
Chapter 11, page 6
Writing to a File
opens the file
data should be buffered,
and we want to use the
well known println()
method
writes one line
to the stream
closes the stream,
and the file with that
FileWriter writeConnToFile = new
FileWriter(filename, true);
PrintWriter printer = new PrintWriter(new
BufferedWriter(writeConnToFile));
String newName = ”Peter Hill”;
printer.println(newName );
printer.close();
Show program listing 11.1 pp. 310-311.
Solve the problems, pp. 314 and 315 (top and bottom).
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 7
Sequential Data Files - Summary
• Sequential data files are opened for reading or writing.
• Reading always starts at the beginning of the file.
• Writing can happen at the beginning of the file or after what is already
there from before.
• For a file to be read, it has to exist in advance.
• If a file to be written to does not already exist, it will be created
automatically.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 8
Reading and Writing to a File
To read from a file
To write to a file
FileReader connection =
new FileReader(fileName)
FileWriter connection =
new FileWriter(fileName,
append)
To create
a read stream object
or a write stream
object
BufferedReader reader =
new
BufferedReader(connection)
PrintWriter reader =
new PrintWriter(new
BufferedWriter(connection))
To read/write to the
stream object
reader.readLine(...)
reader.print(....)
reader.println(....)
To close the stream
object
reader.close()
reader.close()
To open a file
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 9
A Small Selection of the Input and
Output Classes in JDK 1.0
Object
Object
OutputStream
InputStream
FileOutputStream
FilterOutputStream
FileInputStream
PrintStream
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 10
A Small Selection of the Input and Output Classes in
JDK 1.1 and Newer Versions of Java
Object
Object
Reader
Writer
InputStreamReader
BufferedReader
FileReader
OutputStreamWriter
PrintWriter
BufferedWriter
FileWriter
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 11
Reading Numbers from a Data File
1. Input one line of numbers at a time, use the readLine() method.
2. To find the spaces in the string, use the java.util. StringTokenizer
class.
3. A string is converted into a number using the familiar methods
parseInt() and parseDouble().
Show program listing 11.2 page 321.
Solve the problem, pp. 322-323.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 12
Communication with the Console
• Printout is familiar: System.out.println()
• Input from the console is about the same as input from a file:
InputStreamReader readConnConsole = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(readConnConsole);
System.out.print("Your first name: ");
System.out.flush(); // flushes the buffer after print() is used
String firstName = reader.readLine();
• In the console window:
>java …the name of the class…
Your first name: Ann
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 13
The Process of Writing to / Reading from a File
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 14
Data (Numbers) Transferred as Text
versus Binary Data Transfer
• Numbers are stored in the computer memory in binary representation.
• At a data file, they may be saved as text, or they may keep their binary
representation.
• Numbers transferred as text
– The data file may be read by humans using an editor.
– The conversion ("formatting") to / from binary representation takes time.
– If decimal numerals should keep their accuracy, a double should be
written with 15 digits.
• Numbers transferred binary
–
–
–
–
The data file is not readable by humans.
The bytes are transferred directly without conversion.
No time is used for conversion.
The space required is the same at the data file as in the memory.
• Interfaces in the Java API usable for binary transfer
– DataInput
– DataOutput
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 15
Random Access to the Contents of a File
• An instance of the class RandomAccessFile is linked to a file that can
be opened for both reading and writing.
• We can move the file pointer to any position whatsoever in this file.
• The RandomAccessFile class implements the interfaces for binary data
transfer.
• Constructor:
– RandomAccessFile(String fileName, String mode)
• mode = ”r” or ”rw”
– Methods, all may throw IOException:
•
•
•
•
long getFilePointer(), void seek(long pos), long length()
void close()
char readChar(), int readInt(), double readDouble()
void writeChar(int character), void writeInt(int number),
void writeDouble(double decimalNumeral)
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 16
An Example
import java.io.*;
class DirectAccessFile {
public static void main(String[] args) {
try {
RandomAccessFile file =
new RandomAccessFile("DirectFile.dat", "rw");
/* writes 10 integers to the file */
for (int i = 0; i < 10; i++) file.writeInt(i);
long fileLength = file.length();
System.out.println(
"The file is " + fileLength + " bytes long.");
/*
* moves the file pointer to integer no. 7, reads i,
* multiplies it by 10, and rewrites it to the file.
*/
file.seek(6 * 4); // moves past 6 integers, each 4 bytes
int number = file.readInt();
number *= 10;
file.seek(6 * 4); // moves the filepointer "back"
file.writeInt(number);
/* reads the whole file */
file.seek(0); // moves to the beginning of the file
try {
while (true) { // stops when EOFException is thrown
int t = file.readInt();
/* Printout::
System.out.println(t);
The file is
}
40 bytes long.
}
0
catch (EOFException e) {
1
}
2
file.close();
3
} catch (Exception e) {
4
System.out.println("Error: " + e);
5
}
60
}
7
}
8
9
*/
0
1
2
3
4
5
6
7
2
file.seek(6 * 4);
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
3
8
9
1
for (int i = 0; i < 10; i++)
file.writeInt(i);
file.readInt(number)
Chapter 11, page 17
How Saving a Large Object at a File?
• We want to save an instance of the RenovationProject (chap. 10) at
file:
class RenovationProject {
private String name;
private ArrayList allSurfaces = new ArrayList();
private ArrayList allPaints = new ArrayList();
• We have to split the object into smaller parts, and then save each value,
for example in this way:
write the number of surfaces to the file
for (int i = 0; i < project. getNoOfSurfaces(); i++) {
Surface theSurface = project.getSurface(i);
write theSurface's name, length and width, and the name of the paint type, to
the file
}
do the same for all paints
• By reading we have to do the reverse process.
• Or is there another way - ?
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 18
Serialization
• Objects may be serialized.
– The whole object is saved in one single statemment.
– The file is not readable by humans in an editor.
– The file is sequential and is open for reading or writing.
• Writing the myApartment object to file:
FileOutputStream outstream = new FileOutputStream("apartment1.ser");
ObjectOutputStream out = new ObjectOutputStream(outstream);
out.writeObject(myApartment); // (class constants and class variables are not stored)
out.close();
• Reading the object:
FileInputStream instream = new FileInputStream("apartment1.ser");
ObjectInputStream in = new ObjectInputStream(instream);
RenovationProject myApartment = (RenovationProject) in.readObject();
in.close();
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 19
What Is Required for an Object to be Serialized?
•
•
•
Classes describing these objects have to implement the java.io.Serializable
interface
Very easy! The interface doesn't contain any methods at all.
In our case:
– class Surface implements java.io.Serializable {
– class Paint implements java.io.Serializable {
– class RenovationProject implements java.io.Serializable {
•
•
Almost every class in the Java API implements Serializable
What happens in the serialization process?
– Instance variables are saved, class variables are not saved.
– Information about every single class, included version no., is saved.
– A reference to an object implies that the object is saved the first time this reference
is found. The object then gets a serial number (from this is the name of the process;
serialization). The next time the same reference is found, this serial number is used.
•
If the version of the class is not the same when the data are read as it was when
they were written, an InvalidClassException is thrown.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 20
Show Program Listing 11.4 pp. 330-331
Solve the problems, pp. 334-335.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 21
The instanceof operator
operand1 instanceof operand2
reference
•
•
•
•
•
class or interface
A binary operator.
The value of the expression is true if the object is an instance of the class, or of
a subclass of the class.
If the second operand is an interface, the object has to be an instance of a class
(or of a subclass of a class) that implements this interface.
The operator has the same priority as the other comparison operators.
Examples (the classes implements Serializable):
–
–
–
–
–
Paint m1 = new Paint("Heimdal Extra", 3, 10, 100);
m1 instanceof Paint
true
m1 instanceof Surface
false
m1 instanceof Serializable
true
m1 instanceof Object
true
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 22
Summary - Data Files
•
Sequential data files with data
transferred as text (section 11.1-11.7)
– The file is opened for reading or
writing.
– A program reads one line at a time by
using readLine().
– A program writes by using print() and
println().
– Numerical data are converted to/from
text.
– The console is a special case of this
type of file.
– May create a file of this type with an
editor.
•
Binary data transfer (section 11.8)
– Data, both text and numbers, are
transferred without conversion.
– A file of this type has to be created by
a Java-program made for this purpose.
•
Files with random access(section
11.9)
– The file may at the same time be
opened for reading and writing.
– The file is not sequential: The file
pointer may be moved forwards
and backwards.
– Data are transferred binary. In an
editor a human being will only be
able to read data of char type.
•
Serialization (section 11.10)
– This process reads or writes whole
objects.
– The file is handled in a sequential
way.
– The data are not readable in an
editor (except for texts which
could be recognized among very
much other things).
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 11, page 23
Download