写出满足以下条件的Java代码: 创建一学生类(包括姓名、年龄、班级、密码),创建若干该类的对象并保存在文件中(密码可简单加密),从文件读取对象后显示在屏幕上,如果该文件不存在或读取的对象为空,则显示相关异常信息!
时间: 2024-03-14 18:47:06 浏览: 62
好的,以下是满足条件的 Java 代码:
```java
import java.io.*;
import java.util.*;
class Student implements Serializable {
private String name;
private int age;
private String className;
private String password;
public Student(String name, int age, String className, String password) {
this.name = name;
this.age = age;
this.className = className;
this.password = password;
}
public String toString() {
return "姓名:" + name + ",年龄:" + age + ",班级:" + className + ",密码:" + password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
}
public class Main {
private static final String FILE_NAME = "students.dat";
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("张三", 18, "计算机科学与技术1班", "123456"));
students.add(new Student("李四", 19, "计算机科学与技术2班", "654321"));
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_NAME))) {
for (Student student : students) {
// 简单加密密码
student.setPassword(student.getPassword() + "key");
oos.writeObject(student);
}
System.out.println("保存成功!");
} catch (IOException e) {
System.out.println("保存失败!" + e.getMessage());
return;
}
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_NAME))) {
Object obj = ois.readObject();
while (obj != null) {
if (obj instanceof Student) {
Student student = (Student) obj;
// 简单解密密码
student.setPassword(student.getPassword().substring(0, student.getPassword().length() - 3));
System.out.println(student);
}
obj = ois.readObject();
}
} catch (FileNotFoundException e) {
System.out.println("文件不存在!" + e.getMessage());
} catch (IOException e) {
System.out.println("读取失败!" + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("找不到类!" + e.getMessage());
}
}
}
```
这段代码实现了一个简单的功能:创建一个 `Student` 类,包括姓名、年龄、班级、密码等属性,然后创建若干个该类的对象并保存在文件中,密码在保存时进行简单加密。然后从文件中读取对象,解密密码后显示在屏幕上。如果文件不存在或读取的对象为空,则显示相关异常信息。
代码中使用了 `ObjectOutputStream` 和 `ObjectInputStream` 类来实现对象的序列化和反序列化,并使用了 `FileNotFoundException`、`IOException` 和 `ClassNotFoundException` 等异常来处理可能出现的异常情况。
阅读全文