From fc5b2060a6b5adb256266bc7f8de8af90e3e10df Mon Sep 17 00:00:00 2001 From: MahiRenush <43253966+MahiRenush@users.noreply.github.com> Date: Thu, 25 Oct 2018 11:25:31 +0530 Subject: [PATCH] Inserting write of a .ser fiile and read it After knowing a gud level of serialization technique --- Assignment1.java | 58 +++++++++++++++++++++++++++++++----------------- 1 file changed, 38 insertions(+), 20 deletions(-) diff --git a/Assignment1.java b/Assignment1.java index ef1eaee..f1adba9 100644 --- a/Assignment1.java +++ b/Assignment1.java @@ -1,30 +1,48 @@ -package com.Mahi; +import java.util.Scanner; +import java.io.*; -import java.util.*; - -public class Assignment1 { - static Product[] pd; - public static void main(String[] args) { - // TODO Auto-generated method stub +public class Assignment1{ + + + public static void main(String[] args) throws Exception{ + Product[] pd = new Product[6]; Scanner sc= new Scanner(System.in); - String prodID= new String(); + FileOutputStream fos= new FileOutputStream("abc.ser"); + ObjectOutputStream oos= new ObjectOutputStream(fos); float cost=0; - int numberOfItems=0, totalProd=0; - float totcost = 0; - System.out.println("Specify the total no. of products to be bought altogether"); - totalProd= sc.nextInt(); - for(int i=0;i<6;i++){ - System.out.println("Enter the product ID of the "+i+"th item"); + String prodID= new String(); + int noOfItems=0; + float totcost=0; + for(int i=0;i<2;i++){ + System.out.println("Enter the product ID of "+i+"th item"); prodID= sc.next(); - System.out.println("Enter the cost of the "+i+"th item"); + + System.out.println("Enter the cost of "+i+"th item"); cost= sc.nextFloat(); - System.out.println("Enter the total number of items available for "+i+"th item"); - numberOfItems= sc.nextInt(); - pd[i]= new Product(prodID, cost, numberOfItems); + + System.out.println("Enter the total no. of items available in "+i+"th item"); + noOfItems= sc.nextInt(); + + pd[i]= new Product(prodID, cost, noOfItems); + + totcost= totcost+ pd[i].getCost()*pd[i].getNoOfItems(); + oos.writeObject(pd[i]); + + } + Product[] pd1 = new Product[6]; + FileInputStream fis= new FileInputStream("abc.ser"); + ObjectInputStream ois= new ObjectInputStream(fis); + for(int j=0;j<2;j++){ + + + totcost= totcost+ pd[j].getCost()*pd[j].getNoOfItems(); + pd1[j]=(Product)ois.readObject(); + System.out.println(pd1[j]); - totcost= totcost+pd[i].getCost(); - System.out.println(); } + System.out.println("The total cost is "+totcost); sc.close(); + ois.close(); + oos.close(); } }