import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Person implements Serializable {
String name ;
int ssn ;
String phone ;
public Person(String name, int ssn, String phone) {
super();
this.name = name;
this.ssn = ssn;
this.phone = phone;
}
public String toString() {
return name + "/" + ssn + "/" + phone ;
}
public static void writePersons(List
Iterator
ObjectOutputStream out = null ;
try {
out = new ObjectOutputStream(new FileOutputStream(file)) ;
while(iter.hasNext()) {
Person p = iter.next() ;
out.writeObject(p);
}
System.out.println("Data were written") ;
} catch (IOException e) {
e.printStackTrace();
} finally {
try { out.close() ; } catch(Exception e) {}
}
}
public static List
ArrayList
ObjectInputStream in = null ;
try {
in = new ObjectInputStream(new FileInputStream(file)) ;
while(true) list.add((Person) in.readObject()) ;
} catch (IOException e) {
} catch (ClassNotFoundException e) {
} finally { try { in.close(); } catch(Exception e) {} }
return list;
}
public static void printPersons(List
System.out.println("######### Persons ##########") ;
for(Person p : list) {
System.out.println(p);
}
System.out.println("########End of Persons ##########") ;
}
public static void main(String[] args) {
List
BufferedInputStream in = new BufferedInputStream(System.in) ;
boolean isRunning = true ;
while(isRunning) {
System.out.println("1.데이터추가 2.저장 3.읽어오기 4.나가") ;
try {
char data = (char) in.read() ;
switch(data) {
case '1': Person p = getPerson();
if(p != null) persons.add(p) ; break ;
case '2': writePersons(persons , "person.data") ; break;
case '3': persons = readPersons("person.data") ; printPersons(persons) ; break ;
case '4': isRunning = false ; break;
default: System.out.println("Please Select menu!") ; break ;
}
} catch (IOException e) {
e.printStackTrace();
}
}
try { in.close(); } catch (IOException e) { }
}
public static Person getPerson() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)) ;
String name , phone ; int ssn ;
Person p = null ;
try {
System.out.print("Name:") ; name = reader.readLine() ;
System.out.print("Phone:"); phone = reader.readLine() ;
System.out.print("SSN:"); ssn = Integer.parseInt(reader.readLine()) ;
p = new Person(name , ssn , phone) ;
} catch (IOException e) { }
return p ;
}
}
댓글 없음:
댓글 쓰기