ict1414Lecture12

Download Report

Transcript ict1414Lecture12

1
Chapter 12 – Files and Streams 2
Object File I/O
• It is possible to store objects just as easily as you store
primitive data values.
• We use ObjectOutputStream and ObjectInputStream to
save to and load objects from a file.
• To read and write objects from a given class, the class
declaration must include the phrase implements
Serializable. For example,
class Person implements Serializable {
. . .
}
2
Object File Output
• To create an ObjectOutputStream, you need to provide
an outputStream (FileOutputStream in the following
example) argument to the constructor.
File outFile = new File("objects.data");
FileOutputStream outFileStream =
new FileOutputStream(outFile);
ObjectOutputStream outObjectStream=
new ObjectOutputStream(outFileStream);
3
Object File Output
• To write to an ObjectOutputStream, you can use
its writeObject method.
Person person = new Person("Mr. Jackson", 20, 'M');
outObjectStream.writeObject( person );
Account account1 = new Account();
Bank bank1 = new Bank();
outObjectStream.writeObject( account1 );
outObjectStream.writeObject( bank1 );
4
Object File Input
• To create an ObjectInputStream, you need to
provide an InputStream (FileInputStream in the
following example) argument to the constructor.
File inFile = new File("objects.data");
FileInputStream inFileStream =
new FileInputStream(inFile);
ObjectInputStream inObjectStream =
new ObjectInputStream(inFileStream);
5
Object File Input
• To read from an ObjectInputStream, you can use its
readObject method.
• The object read from the file must be casted to the correct
type explicitly.
• Must type cast to the correct object type.
Person person = (Person) inObjectStream.readObject( );
• Must read in the correct order.
Account account1
= (Account) inObjectStream.readObject( );
Bank bank1
= (Bank) inObjectStream.readObject( );
6
Example
• To write two Student objects to a file student.dat.
import java.io.*;
public class Student implements Serializable {
private int studNum;
private String firstName, lastName;
private double mark;
// constructor sets values
public Student(int num, String first, String last,
double mark) {
studNum = num;
firstName = first;
lastName = last.toUpperCase();
this.mark = mark;
}
public String toString() {
return "No. : " + studNum + " Name : " + firstName + " "
+ lastName + " Mark : " + mark;
}
}
// end class Student
7
Example (Cont.)
• Program to write Student objects.
import java.io.*;
class WriteStudentRecord {
public static void main(String[] args) {
Student student1 = new Student(71529, "Tony", "LEE", 76.7);
Student student2 = new Student(68813, "Mary", "WONG",
55.8);
try {
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(new File("student.dat")));
oos.writeObject(student1);
oos.writeObject(student2);
oos.close();
} catch (IOException ioe) {
System.out.println("Error : " + ioe);
}
}
}
8
Example (Cont.)
• Program to read and display Student objects.
import java.io.*;
class ReadStudentRecord {
public static void main(String[] args) {
Student student1;
Student student2;
try {
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream(
new File("student.dat")));
student1 = (Student) ois.readObject();
student2 = (Student) ois.readObject();
System.out.println(student1);
System.out.println(student2);
ois.close();
} catch (Exception e) {
System.out.println("Error : " + e);
}
}
}
Output
No. : 71529
No. : 68813
Name : Tony LEE Mark : 76.7
Name : Mary WONG Mark : 55.8
9
Saving and Loading Arrays
• Instead of processing array elements individually, it is
possible to save and load the whole array at once.
• Write an array of objects:
Person[] people = new Person[ N ];
//build the people array
...
//save the array
outObjectStream.writeObject ( people );
• Read an array of objects:
Person[ ] inPeople = (Person[ ]) inObjectStream.readObject ( );
10
Example
• Program to write an array of 4 Student objects.
import java.io.*;
class WriteStudentArray {
public static void main(String s[]) {
Student students[] = new Student[4];
students[0] = new Student(71529, "Tony", "LEE", 76.7);
students[1] = new Student(68813, "Mary", "WONG", 55.8);
students[2] = new Student(90912, "Oscar", "CHEUNG", 66.7);
students[3] = new Student(81276, "Peter", "HUNG", 72.1);
try {
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(new File("stud_arr.dat")));
oos.writeObject(students);
oos.close();
} catch (IOException ioe) {
System.out.println("Error : " + ioe);
}
}
}
11
Example (Cont.)
• Program to read and display an array of Student objects.
import java.io.*;
class ReadStudentArray {
public static void main(String s[]) {
Student[] students;
try {
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream(new File("stud_arr.dat")));
students = (Student[]) ois.readObject();
for (int i=0; i < students.length; i++) {
System.out.println(students[i]);
}
must catch
}
}
ois.close();
ClassNotFoundException as well
} catch (Exception e) {
System.out.println("Error : " + e);
}
Output
No.
No.
No.
No.
:
:
:
:
71529
68813
90912
81276
Name
Name
Name
Name
:
:
:
:
Tony LEE Mark : 76.7
Mary WONG Mark : 55.8
Oscar CHEUNG Mark : 66.7
Peter HUNG Mark : 72.1
12
Text IO vs Object IO
• The advantages of using Text IO
– ASCII text can be understood by any text editor.
– The file can be edited by hand if you wish to change
information.
– The receiver and sender do not have to rely on common
classes
• The advantages of using Object IO
– Simple read and write operations, no conversion
required
– Data stored in binary format - usually take less space
13
JFileChooser - Open
• JFileChooser is a standard file dialog for selecting a file.
14
JFileChooser - Open
• Example : Use JFileChooser to open a file and print its
name to the console.
import java.io.*;
import javax.swing.*;
Display the
chooser
public class FileChooserDemo {
public static void main(String[] args) {
JFileChooser fc = new JFileChooser();Check whether "Open"
int returnVal = fc.showOpenDialog(null);
button is pressed
if (returnVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
Get the
System.out.println("Opening: "
selected file
+ file.getName());
} else {
System.out.println(
"Open command cancelled by user.");
}
}
}
15
JFileChooser - Save
• You can use showSaveDialog() to display a save
dialog.
int returnVal = fc.showSaveDialog(null);