5-3作业

来源:5-3 自由编程

J_DP

2020-03-21 21:19:03

package com.imooc.filework;


import java.io.Serializable;


public class Product implements Serializable{

//id产品id,name产品名称,categories产品属性,price产品价格

private int id;

private  String name;

private  String categories;

private  double price;

static{

System.out.println("apple系列产品信息:");

}

public Product() {

}

    public Product(int id,String name,String categories,double price) {

this.setId(id);

this.setName(name);

this.setCategories(categories);

this.setPrice(price);

}


public int getId() {

return id;

}


public void setId(int id) {

this.id = id;

}


public String getName() {

return name;

}


public void setName(String name) {

this.name = name;

}


public String getCategories() {

return categories;

}


public void setCategories(String categories) {

this.categories = categories;

}


public double getPrice() {

return price;

}


public void setPrice(double price) {

this.price = price;

}

@Override

public String toString() {

return "产品id:" + id + " \n产品名称:" + name + "\n产品属性:" + categories + "\n产品价格:" + price + "元";

}

}

package com.imooc.filework;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

public class Test {

public static void main(String[] args) {

Product p1  = new Product(123,"手机","telephone",4888);

Product p2  = new Product(234,"平板电脑","computer",5088);

Product p3  = new Product(345,"MacBook","Mac",10668);

Product p4  = new Product(256,"手表","watch",4888);

try {

FileOutputStream f = new FileOutputStream("/Users/dong/Product.txt");

ObjectOutputStream bos = new ObjectOutputStream(f);

FileInputStream f1 = new FileInputStream("/Users/dong/Product.txt");

ObjectInputStream bis = new ObjectInputStream(f1);

bos.writeObject(p1);

bos.writeObject(p2);

bos.writeObject(p3);

bos.writeObject(p4);

bos.flush();

for(int i = 0;i<4;i++) {

Product p =(Product)bis.readObject();

System.out.println(p);

System.out.println();

}

bis.close();

f.close();

bos.close();

f1.close();

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}


写回答

1回答

好帮手慕阿慧

2020-03-22

同学你好,程序正确,做的很好。继续加油。祝学习愉快~

0

0 学习 · 11489 问题

查看课程