如何创建文件,并将对象写进文件?
1、分别创建对象类,文件所在类
2、将文件写进流中,在将对象写进去
3、将文件写进流中,再读出来,强制类型转换得到
读入与读出
package com.vetor;
import java.io.*;
public class ReadWriteObject {
public static void main(String[] args) {
Student w1 = new Student("张三",20,"计算机系");//创建两个对象
Student w2 = new Student("李四",21,"金融系");
FileOutputStream fout; //声明输入对象,指文件对象
ObjectOutputStream dout; //指输出流对象
FileInputStream fin; //声明输出对象
ObjectInputStream din;
File f = new File("ReadWriteObject.txt");
//创建文件
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try
{
fout = new FileOutputStream(f);
dout = new ObjectOutputStream(fout);
dout.writeObject(w1);//流对象传进取类对象
dout.writeObject(w2);
dout.close(); //关闭流
}
catch (Exception e){
e.printStackTrace();
}
try {
fin = new FileInputStream(f);
din = new ObjectInputStream(fin);
Student r1 = (Student) din.readObject(); //读取一个对象转换问Student对象
System.out.println(r1.toString()); //调用r1的方法输出它的信息
Student r2 = (Student) din.readObject();
System.out.println(r2.toString());
din.close(); //关闭输出流
}
catch (Exception e)
{
System.out.println(e);
}
}
}
具体对象
代码如下(示例):
package com.vetor;
import java.io.*;
class Student implements Serializable {
String name;
int age;
String dept;
public Student(String newName,int newAge,String newDept) { //初始化变量
name = newName;
age = newAge;
dept = newDept;
}
public String toString() { //输出对象信息
return name+""+age+""+dept;
}
}