将Java对象的属性保存到文本文件中,保存的对象为People类型,属性:id、name、age、address。并完成读取出来封装成对象

将Java对象的属性保存到文本文件中,保存的对象为People类型,属性:id、name、age、address。并完成读取出来封装成对象

写出文件

 public static void main(String[] args) {
        People people = new People(1001,"张三",19,"天津市北辰区");
        String data = people.getId()+"#"+people.getName()+"#"+people.getAge()+"#"+people.getAddress();
        byte[] buf = data.getBytes();
        File file = new File("c:/1.txt");
        try {
            FileOutputStream fos = new  FileOutputStream(file);

            fos.write(buf);
            fos.close();
            System.out.println("写入成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

读入文件

    public static void main(String[] args) {
        File file = new File("c:/1.txt");

        try {
            FileInputStream fis = new FileInputStream(file);
            byte[] buf = new byte[100];
            int len = fis.read(buf);
            String str = new String(buf,0,len);
            System.out.println("读取的数据是:"+str);
            fis.close();

            String[] ss = str.split("#");
            for (String s : ss) {
                System.out.println(s);
            }

            People people = new People(Integer.parseInt(ss[0]),ss[1],Integer.parseInt(ss[2]),ss[3]);
            System.out.println("对象:"+people);

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

读入和写出

 public static void main(String[] args) {
        People people = new People(1001,"张三",18,"天津市");

        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("e:/people.txt"));
            oos.writeObject(people);

            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("e:/people.txt"));
            People people1 = (People) ois.readObject();
            System.out.println(people1);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值