我正在尝试制作一个程序来存储我表示为条目的类的数组。此类存储基于命令、名称、编号和注释的用户输入。接收到条目后,将通过 ObjectInput/ObjectOutput 将其发送到文件,并存储以供以后使用。
有点像一个简单的联系人列表,可以定期调用和不时更新。
我遇到了一种奇怪的错误(见下文)。如果有人可以帮助我解决此错误,我将不胜感激。
代码:
import java.io.*;
import java.util.Scanner;
public class phonebook {
protected Entry[] entryList = new Entry[200];
protected int length = 0;
public void doList() {
for (int i=0; i<length; i++) {
System.out.print(entryList[i]);
}
}
public void doAddEntry(Entry entry) throws Exception {
if (length == 200) {
throw new Exception("I'm full");
}
for (int i = 0; i<length; i++) {
if (entryList[i].name.compareToIgnoreCase(entry.name) <0) {
//?
}
}
}
public void doFind(String term) {
// look for input in entryList's name fields
}
public void doSave() throws Exception {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("contacts.txt"));
os.writeObject(entryList);
os.close();
}
public void doLoad() throws Exception {
***ObjectInputStream oin = new ObjectInputStream(new FileInputStream("contacts.txt"));***
entryList = (Entry[])oin.readObject();
oin.close();
}
public static void main(String[] args) throws Exception {
String line;
String[] command;
Scanner input;
String delimeter;
delimeter = " ";
phonebook pbook;
String cmd;
String term;
pbook = new phonebook();
cmd= "";
input=new Scanner (System.in);
**pbook.doLoad();**
System.out.println("Codes are entered as 1 to 8 characters");
System.out.println("Use \"e\" for enter, \"f\" for find, \"l\" to list, and \"q\" to quit");
System.out.println();
do {
System.out.print("Command: ");
line = input.nextLine();
command = line.split(delimeter);
if (command[0].equalsIgnoreCase("e")) {
Entry e = new Entry();
e.name = command[0];
System.out.print("Enter Number: ");
e.number=input.nextLine();
System.out.print("Enter Notes: ");
e.notes=input.nextLine();
System.out.println("");
pbook.doAddEntry(e);
} else if (command[0].equalsIgnoreCase("f")) {
term=command[0];
pbook.doFind(term);
} else if (command[0].equalsIgnoreCase("l")) {
pbook.doList();
} else if (command[0].equalsIgnoreCase("q")) {
System.out.println("Exiting Program...");
pbook.doSave();
break;
} else {
System.out.println("Invalid Command");
continue;
}
} while (true);
}
}
班级:
public class Entry implements java.io.Serializable {
public String name;
public String number;
public String notes;
}
编译器错误消息(代码引用错误可以在上面的*之间找到):
Exception in thread "main" java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at phonebook.doLoad(phonebook.java:39)
at phonebook.main(phonebook.java:57)