public boolean register(User user) {
if (f.length() != 0) {
try {
ois = new ObjectInputStream(new FileInputStream(f));
oos = new ObjectOutputStream(new FileOutputStream(f));
for(int i = 0; i < list.size(); i++) {
if (list.get(i).getUid() != null) {
if (list.get(i).getUid().substring(0, 5).equals("10000")) {
i -=1;
id = 10000 + i + "";
User us = new User(id, user.getUserName(), user.getPassword());
list.add(us);
oos.writeObject(list);
oos.flush();
return true;
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
bank.realse(ois);
bank.realse(oos);
}
}else {
try {
oos = new ObjectOutputStream(new FileOutputStream(f));
id = 10000 + "" + 1;
User us = new User(id, user.getUserName(), user.getPassword());
list.add(us);
oos.writeObject(list);
oos.flush();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
bank.realse(ois);
bank.realse(oos);
}
}
return false;
}
调用语句为:
String name = jtf1.getText();
String password = jtf2.getText();
User u = new User(name, password);
Serviceimpl ser = new Serviceimpl();
if (ser.register(u)) {
JOptionPane.showMessageDialog(jButton1, "注册成功!");
} else {
JOptionPane.showMessageDialog(jButton1, "注册失败!");
}
jtf1.setText("");
jtf2.setText("");
只能注册一个帐户,注册第二个时就注册失败,且清空第一个,请高手帮忙看看什么原因,谢谢!

解决方案 »

  1.   

    问题应该在你的User的构造函数里面吧..里面有没有对ID重复之类的进行检查? 
    另外, 你的register函数是只注册一个吧? 根据你的for循环来看, 一旦注册成功, 就马上返回了.
      

  2.   

    ois = new ObjectInputStream(new FileInputStream(f));
    oos = new ObjectOutputStream(new FileOutputStream(f));
    list = (List<User>)ois.readObject();
    System.out.println(list);
    for(int i = 0; i < list.size(); i++) {
    if (list.get(i).getUid() != null) {
    if (list.get(i).getUid().substring(0, 5).equals("10000")) {
    i -=1;
    id = 10000 + i + "";
    User us = new User(id, user.getUserName(), user.getPassword());
    list.add(us);
    oos.writeObject(list);
    oos.flush();
    return true;
    }
    }
    }
    在执行完list = (List<User>)ois.readObject();后就跳出EOFException - java.io 中的 异常
    当输入过程中意外到达文件或流的末尾时,抛出此异常。
      

  3.   

    将oos = new ObjectOutputStream(new FileOutputStream(f));移到
    User us = new User(id, user.getUserName(), user.getPassword());
    后面就可以了,谢谢各位的回答。