The WriteFile class:
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
public class WriteFile implements Serializable{
private FileInputStream fis;
private ObjectInputStream ois;
private FileOutputStream fos;
private ObjectOutputStream oos;
private ArrayList<Student> list;
public WriteFile(String f, ArrayList<Student> a) {
list = new ArrayList<Student>(a.size());
//performs a deep copy
for(int i=0; i<a.size(); i++) {
this.list.add(i, a.get(i));
}
try {
fos = new FileOutputStream(f);
oos = new ObjectOutputStream(fos);
fis = new FileInputStream(f);
ois = new ObjectInputStream(fis);
}
catch(FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "File not found");
System.exit(0);
}
catch(IOException e) {
JOptionPane.showMessageDialog(null, "Could not make a connect with the file");
}
}
public void write(Student s){
try {
oos.writeObject(s);
oos.close();
}
catch(IOException e) {
JOptionPane.showMessageDialog(null, "An error has occured");
}
}
public void write(int i){
try {
oos.writeObject(list.get(i));
oos.close();
}
catch(IOException e) {
JOptionPane.showMessageDialog(null, "An error has occured");
}
}
public Student read() throws IOException, ClassNotFoundException {
return (Student) ois.readObject();
}
}
My driver class:
import java.io.*;
import java.util.*;
public class TestClass {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ArrayList<Student> list = new ArrayList<Student>(0);
int i = 0;
while(i < 5) {
list.add(i, new Student("John", "Smith", "777555333", "Comp Sci"));
i++;
}
WriteFile file = new WriteFile("students.dat", list);
file.write(0);
list.add(file.read());
System.out.println(list.get(5));
}
}
Heres my output:
First Name: Last Name: Student ID: 777555333 Major: Comp Sci

New Topic/Question
Reply



MultiQuote




|