麻烦老师帮忙批改,谢谢

来源:5-3 自由编程

ByteDancer07

2020-01-14 19:33:13

Product类

package com.kai.practise;

import java.io.Serializable;

public class Product implements Serializable {
	private int id;
	private String name;
	private String categoris;
	private double price;
	
	public Product() {
	
	}
	//获取所有属性的构造方法
	public Product(int id, String name, String categoris, double price) {
		
		this.setId(id);
		this.setName(name);
		this.setCategoris(categoris);
		this.setPrice(price);
	}
	
	//getter和setter 方法
	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 getCategoris() {
		return categoris;
	}
	public void setCategoris(String categoris) {
		this.categoris = categoris;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	
	//重写toString()方法
	@Override
	public String toString() {
		return "产品ID:"+this.getId()+"\n产品名称:"+this.getName()+"\n产品属性:"+
	this.getCategoris()+"\n产品价格:"+this.getPrice()+"元";
		
	}
	
	
	
}

Test类

package com.kai.practise;

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对象:iphone,ipad,macbook,iwatch
		Product one = new Product(123,"iphone","telephone",4888.0);
		Product two = new Product(234,"ipad","computer",5088.0);
		Product three = new Product(345,"macbook","computer",10688.0);
		Product four = new Product(256,"iwatch","watch",4799.0);
		
		//实例化对象输入输出流
		try {
			FileOutputStream file = new FileOutputStream("product.txt");
			ObjectOutputStream objOutput = new ObjectOutputStream(file);
			FileInputStream file2 = new FileInputStream("product.txt");
			ObjectInputStream objInput = new ObjectInputStream(file2);
			
			objOutput.writeObject(one);
			objOutput.writeObject(two);
			objOutput.writeObject(three);
			objOutput.writeObject(four);
			objOutput.flush();
			
			Product oneInput = (Product)objInput.readObject();
			Product twoInput = (Product)objInput.readObject();
			Product threeInput = (Product)objInput.readObject();
			Product fourInput = (Product)objInput.readObject();
			
			//在控制台输出产品信息
			System.out.println("apple系列产品信息:");
			System.out.println(oneInput+"\n");
			System.out.println(twoInput+"\n");
			System.out.println(threeInput+"\n");
			System.out.println(fourInput);

			
			file.close();
			file2.close();
			objOutput.close();
			objInput.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}catch(ClassNotFoundException e) {
			e.printStackTrace();
		}

	}

}


写回答

1回答

好帮手慕小尤

2020-01-15

已完成练习,棒棒哒!继续加油!

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!

0

0 学习 · 11489 问题

查看课程