java学生类写入文件
时间: 2023-08-30 20:05:53 浏览: 59
要将Java中的学生类写入文件,您可以将学生类的对象转换为字符串,然后将其写入文件中。下面是一个示例代码,可以将学生对象写入文件:
```java
import java.io.*;
public class Student implements Serializable {
private int id;
private String name;
private int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String toString() {
return "ID: " + id + "\nName: " + name + "\nAge: " + age + "\n";
}
public static void main(String[] args) {
Student s = new Student(1, "John", 20);
try {
FileOutputStream fos = new FileOutputStream("student.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s.toString());
oos.close();
fos.close();
System.out.println("Student object has been written to file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们将学生对象转换为字符串,并使用ObjectOutputStream将其写入文件中。请注意,我们需要在类的声明中实现Serializable接口,以便Java可以将对象序列化并写入文件。