用java中objectoutputstream写一个用户输入信息和储存和输出信息的代码
时间: 2023-05-20 13:06:18 浏览: 95
以下是一个简单的示例代码,用于使用Java中的ObjectOutputStream类将用户输入的信息存储并输出:
import java.io.*;
public class UserInfo implements Serializable {
private String name;
private int age;
private String email;
public UserInfo(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
public static void main(String[] args) {
UserInfo user = new UserInfo("John Doe", 30, "johndoe@example.com");
try {
FileOutputStream fileOut = new FileOutputStream("user.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(user);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in user.ser");
} catch (IOException i) {
i.printStackTrace();
}
try {
FileInputStream fileIn = new FileInputStream("user.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
UserInfo savedUser = (UserInfo) in.readObject();
in.close();
fileIn.close();
System.out.println("Name: " + savedUser.getName());
System.out.println("Age: " + savedUser.getAge());
System.out.println("Email: " + savedUser.getEmail());
} catch (IOException i) {
i.printStackTrace();
} catch (ClassNotFoundException c) {
System.out.println("UserInfo class not found");
c.printStackTrace();
}
}
}
请注意,此示例代码仅用于演示目的。在实际应用中,您需要根据您的需求进行修改和调整。
阅读全文