文件与对象

如何创建文件,并将对象写进文件?

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;
    }
}

结果如下:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值