Skip to content

Instantly share code, notes, and snippets.

@mirsahib
Created February 26, 2017 16:25
Show Gist options
  • Save mirsahib/05450b05736e760d8f2efea6bffa93e4 to your computer and use it in GitHub Desktop.
Save mirsahib/05450b05736e760d8f2efea6bffa93e4 to your computer and use it in GitHub Desktop.
import java.io.*;
import java.util.*;
class Student implements Serializable{
private int id;
private String name;
public void getData(){
int i;
String n;
Scanner input = new Scanner(System.in);
System.out.println("Enter ID:");
i = input.nextInt();
input.nextLine();
System.out.println("Enter Name:");
n = input.nextLine();
this.setId(i);
this.setName(n);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString(){
String temp="ID: "+this.id+" Name: "+this.name;
return temp;
}
}
class StudentArray{
private Student [] s;
public StudentArray(){
s = new Student[3];
try{
//writing file
FileOutputStream fout = new FileOutputStream("course.ser");
ObjectOutputStream out = new ObjectOutputStream(fout);
for(int i=0;i<3;i++){
s[i] = new Student();
s[i].getData();
out.writeObject(s[i]);
}
out.flush();
System.out.println("Success");
out.close();
}catch(Exception e){
System.out.println(e);
}
}
public void displayStudent(){
try{
//reading file
FileInputStream fin = new FileInputStream("course.ser");
ObjectInputStream in = new ObjectInputStream(fin);
Student s = null;
while((s=(Student)in.readObject())!=null){
System.out.println(s);
}
in.close();
}catch(Exception e){
System.out.println(e);
}
}
}
public class TestAssignment {
public static void main(String[] args) {
StudentArray s = new StudentArray();
s.displayStudent();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment