我有这个可以输入信息的User类。但是,一旦主方法关闭,信息就会丢失。我想知道如何将所有信息存储到结构中的文本文件中,如下所示。
用户名
收件箱中的邮件数量
message1 sender
message1 receiver
message1 subject
message1 body
message2 sender
message2 receiver
message2 subject
message2正文 ...
消息类
public class Message {
// the properties of a message
private String sender;
private String receiver;
private String subject;
private String body;
// all property values are known at creation of the message; so initialize
public Message (String s, String r, String sub, String b)
{
sender = s;
receiver = r;
subject = sub;
body = b;
}
// any nice format of printing the names and the values of the properties will do
public void printMsg()
{
System.out.println("Sender: " + sender);
System.out.println("Receiver: " + receiver);
System.out.println("Subject: " + subject);
System.out.println("Message: " + body);
}
// what follows are basic getter methods
public String getSender()
{
return sender;
}
public String getReceiver()
{
return receiver;
}
public String getSubject()
{
return subject;
}
public String getBody()
{
return body;
}
}
用户类
import java.util.ArrayList;
public class Userlist
{
private ArrayList<User> users;
private int numUsers;
public Userlist()
{
users = new ArrayList<User>();
}
public User findUser(String username)
{
for (User i : users)
{
if (i.userName.equals(username))
return i;
}
return null;
}
public void addUser(User u)
{
if (findUser(u.userName) != null)
System.out.println("User already exists");
else
{
users.add(u);
numUsers++;
}
}
public int getNumUsers()
{
return this.numUsers;
}
public User getUser(int i)
{
if (i>=users.length)
return null;
else
return users.get(i-1);
}
}
答案 0 :(得分:1)
技术1:人类可读格式
如果您需要以人类可读的格式存储它,您有以下选择:
1)将其存储为JSON(您可以查看GSON库,其使用起来相当简单)
2)以XML格式存储
3)你需要编写逻辑来将对象转换为字符串表示(这可能是很多工作)
技术2:二进制文件
将对象的内容/状态存储到文件的过程称为序列化。您可以查看以下教程:Java - Serialization
在main方法退出之前,您可以通过序列化用户对象将对象序列化为某个文件。此外,当您序列化用户A的对象时,您可以序列化该用户的所有消息。
首先,您需要声明要序列化为Serializable的所有类:
public class UserList implements Serializable
{
}
public class Message implements Serializable
{
}
然后,对于序列化/反序列化,您可以使用以下代码:
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(fos);
UserList userList ; // assume this is the object to be serialized
out.writeObject(userList); // serializes the object
从文件中取回对象(反序列化):
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(fis);
userList = (UserList) in.readObject();