我有管理帐户,应该能够添加许多用户到。dat文件。然后,我想从.dat文件中检索所有对象到一个列表中,以便进一步编程。
public class User implements Serializable { //get and set methods }
这是我写入每个对象到。dat文件
public void addNewUser() throws Exception {
User newUser=new User();
newUser.name="test";
newUser.position="admin";
FileOutputStream outStream = new FileOutputStream("Users.dat", true);
ObjectOutputStream objectOutputFile = new ObjectOutputStream(outStream);
// Write the object to the file.
objectOutputFile.writeObject(newUser);
// Close the file.
objectOutputFile.close();
}
如何从。dat文件中检索所有对象到ArrayList??
public class displayUsers { **//what to do??** }
您可以写入列表对象并将其作为列表读取。但由于你是单独编写用户对象,你可以这样做-
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Users.dat"));
Object object = null;
while ((object = ois.readObject()) != null) {
if (object instanceof User) {
User user = (User) object;
list.add(user);
}
}
当然,您需要注意异常(如EOFException)。
一般来说,不添加任何长度或分隔符就将单个ObjectOutputStream
连接到文件中是不好的做法。因此,最好一次写入所有对象(并使用ObjectOutputStream.reset
,以防您的进程长时间运行并且担心内存泄漏(否则ObjectOutputStream将保留对之前序列化的每个对象的引用),或者将它们添加到List中并写入。
如果您必须在多个通道中写入它,我建议首先将单个对象写入ByteArrayOutputStream
,然后使用DataOutputStream
写入以其长度为前缀的数组。这样,您就可以使用DataInputStream
取出单个字节数组,并使用ByteArrayInputStream
对它们进行反序列化。
如果这不起作用,您可以尝试以下解决方案(取决于ObjectInputStream
使用的前瞻性,但这可能不适用于具有自定义序列化格式的更复杂对象,因此请自行承担风险):
public static void displayUsers() throws Exception {
FileInputStream fiis = new FileInputStream("Users.dat");
InputStream fis = new FilterInputStream(fiis) {
@Override
public void close() throws IOException {
// ignore
}
};
try {
while (true) {
ObjectInputStream in = new ObjectInputStream(fis);
User user = (User) in.readObject();
in.close();
System.out.println(user.name + "/" + user.position);
}
} catch (EOFException ex) {
// done
}
fiis.close();
}
List<User> listOfUser = new ArrayList<User>();
ObjectInputStream input = null;
try {
while (true) {
input = new ObjectInputStream(new FileInputStream("Users.dat"));
listOfUser.add(input.readObject());
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
input.close();
}