当我从主目录调用“读取文件”时,它仅给我对象,但同一事物在其他应用程序上也起作用,而我的写操作不带参数? 请建议对此代码进行必要的更改。 另外,请解释为什么这不起作用。 谢谢您的时间:)
public class FileIo {
String location = "D:\\Swabhav\\Swabhav\\Practice\\Contact.txt";
public void writeToFile(String fName, String lName, long phoneNo, String emailId)
throws IOException {
Vector<Contact> val = new Vector<Contact>();
val.add(new Contact(fName, lName, phoneNo, emailId));
FileOutputStream fos = new FileOutputStream(location, true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(val);
oos.close();
}
public void displayFile() throws Exception {
FileInputStream fis = new FileInputStream(location);
ObjectInputStream ois = new ObjectInputStream(fis);
Vector<Contact> deserialize = (Vector<Contact>) ois.readObject();
System.out.println(deserialize);
Iterator<Contact> iter = deserialize.iterator();
while(iter.hasNext()) {
Contact v = iter.next();
System.out.println(v.getfName() + " " +
v.getlName() + " " +
v.getEmailId() + " " +
v.getPhoneNo());
}
ois.close();
}
}
public class MainMenu {
Scanner sc = new Scanner(System.in);
FileIo fileObj = new FileIo();
public static void main(String[] args) {
MainMenu mm = new MainMenu();
try {
mm.openMenu();
} catch (Exception e) {
System.out.println(e.getStackTrace());
System.out.println(e.getMessage());
}
}
public void openMenu() throws Exception {
MainMenu mm = new MainMenu();
System.out.println("1. Add Contact.\n2. Display Contacts."
+ "\n3 Search Contact.\n4 Exit");
//System.out.println("Total Number of contacts: " +fileObj.readFromFile());
System.out.println("Enter your choice(1-4): ");
int choice = sc.nextInt();
switch(choice) {
case 1 :
System.out.println("Enter First Name: ");
String fName = sc.next();
System.out.println("Enter Last Name: ");
String lName = sc.next();
System.out.println("Enter mobile number: ");
long phoneNo = sc.nextLong();
System.out.println("Enter e-mail ID: ");
String emailId = sc.next();
fileObj.writeToFile(fName, lName, phoneNo, emailId);
System.out.println("Contact Added");
openMenu();
case 2 :
fileObj.displayFile();
openMenu();
case 4 :
System.out.println("Thank You");
System.exit(0);
}
}
}
public class Contact implements Serializable, Comparable {
private String fName;
private String lName;
private long phoneNo;
private String emailId;
public String getfName() {
return fName;
}
public String getlName() {
return lName;
}
public long getPhoneNo() {
return phoneNo;
}
public String getEmailId() {
return emailId;
}
public Contact(String fName, String lName, long phoneNo, String emailID) {
this.fName = fName;
this.emailId = emailID;
this.lName = lName;
this.phoneNo = phoneNo;
}
@Override
public int compareTo(Object o) {
Contact val = (Contact) o;
return this.fName.compareTo(val.getfName());
}
}