Java语言设计程序完成: (1)消息类,包括发送人,接受人,发消息的时间、消息内容等。 (2)把若干个消息对象存到文件中。 (3)从文件中读入若干消息对象,并输出到控制台。
时间: 2024-09-30 22:13:05 浏览: 36
在Java中,我们可以创建一个`Message`类来表示消息,包含以下几个属性:`sender`(发送人)、`receiver`(接受人)、`timestamp`(发送时间)以及`content`(消息内容)。这个类可以有构造函数设置初始值,以及getter和setter方法以便于操作。
```java
public class Message {
private String sender;
private String receiver;
private Date timestamp;
private String content;
// 构造函数
public Message(String sender, String receiver, Date timestamp, String content) {
this.sender = sender;
this.receiver = receiver;
this.timestamp = timestamp;
this.content = content;
}
// getter and setter methods
public String getSender() { return sender; }
public void setSender(String sender) { this.sender = sender; }
// ... repeat for other properties
}
```
接下来,我们可以创建一个`MessageSerializer`类用于将消息对象序列化并存储到文件中:
```java
import java.io.*;
import java.util.ArrayList;
public class MessageSerializer {
public static void saveMessages(ArrayList<Message> messages, String filename) throws IOException {
try (FileOutputStream fileOut = new FileOutputStream(filename);
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut)) {
objectOut.writeObject(messages);
}
}
}
```
读取文件并反序列化回消息对象的`MessageDeserializer`类:
```java
import java.io.*;
import java.util.ArrayList;
public class MessageDeserializer {
public static ArrayList<Message> readMessages(String filename) throws IOException, ClassNotFoundException {
try (FileInputStream fileIn = new FileInputStream(filename);
ObjectInputStream objectIn = new ObjectInputStream(fileIn)) {
return (ArrayList<Message>) objectIn.readObject();
}
}
}
// 使用示例
ArrayList<Message> messages = new ArrayList<>();
// ...添加消息到messages
MessageSerializer.saveMessages(messages, "messages.txt");
ArrayList<Message> loadedMessages = MessageDeserializer.readMessages("messages.txt");
for (Message msg : loadedMessages) {
System.out.println(msg.toString());
}
```
阅读全文