NowtherehaveaclassnamedPerson:
publicclassPerson{
publicstaticintlastId=0;
privateStringname;
privateDatedateOfBirth;
privateStringaddress;
publicPerson(Stringname,DatedateOfBirth,Stringaddress){
super();//NowIdon’twhatit’s.WhenIsearchit,Ionlyknowthatsuperisthesameasparentclass.Usingsuper()meansthatsubclasscaninvokealltheparentclass’smethods.
this.name=name;
this.dateOfBirth=dateOfBirth;
this.address=address;
lastId++;
this.idNumber=lastId;
}
publicStringtoString(){
return"Person[name="+name+",dateOfBirth="+dateOfBirth
+",address="+address+",idNumber="+idNumber+",phoneNum="+phoneNum+"]";
}
publicStringflatten(){
returnname+","+dateOfBirth.getTime()+","+address+","+phoneNum+","+idNumber;
}
}
StorethePerson’smessage:
publicstaticvoidstoreObjects(Person[]arr){
Filefile=newFile("PersonFile.txt");
try{
BufferedWriterfw=newBufferedWriter(newFileWriter(file,true));
for(inti=0;i<arr.length;i++){
fw.write(arr[i].flatten());//ToinvokePerson.flatten()tostroemessagebysomerules.
fw.newLine();
}
fw.flush();
fw.close();
}catch(IOExceptione){
}
}
Readthe.txt’smessages
publicstaticbooleanreadObjects(Person[]arr){
Filefile=newFile("PersonFile.txt");
Stringline;
Personx;
Stringname;
Datedob;
Stringaddress;
intid;
intposition=0;
try{
BufferedReaderfr=newBufferedReader(newFileReader(file));
while((line=fr.readLine())!=null){
String[]s=line.split(",");
//Themessagewestroearelikingthat:
//Weusinga(Stringline)toreceiveonelinemessage,theninvodeline.split(",")togetaString[].
name=s[0];
dob=newDate(Long.parseLong(s[1]));
address=s[2];
id=Integer.parseInt(s[3]);
x=newPerson(name,dob,address);
arr[position]=x;
position++;
}
fr.close();
}catch(IOExceptione){
returnfalse;
}
returntrue;
}
自己不喜欢的人,可以报之以沉默微笑;