Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.Serializable;
- public class Rectangle implements Serializable
- {
- private double length, width;
- public Rectangle(double l, double w)
- {
- length = l; width = w;
- }
- public void setDimension(double l, double w)
- {
- length = l; width = w;
- }
- public double getArea()
- {
- return length * width;
- }
- public String toString()
- {
- return length + " x " + width + " = " + getArea();
- }
- }
- ============================================
- import java.io.*;
- import java.util.*;
- public class Main
- {
- public static void main(String[] args)
- {
- }
- public static void readList()
- {
- try(ObjectInputStream is =
- new ObjectInputStream(
- new FileInputStream("list.dat")))
- {
- Object data = is.readObject();
- ArrayList<Rectangle> rList =
- (ArrayList<Rectangle>)data;
- Iterator<Rectangle> itor = rList.iterator();
- while (itor.hasNext())
- System.out.println(itor.next());
- }
- catch(FileNotFoundException e)
- {
- System.out.println(e);
- }
- catch(IOException | ClassNotFoundException e)
- {
- System.out.println(e);
- }
- }
- public static void saveList()
- {
- try(ObjectOutputStream os =
- new ObjectOutputStream(
- new FileOutputStream("list.dat")))
- {
- ArrayList<Rectangle> rList = new ArrayList();
- rList.add(new Rectangle(10, 1));
- rList.add(new Rectangle(20, 2));
- rList.add(new Rectangle(30, 3));
- os.writeObject(rList);
- }
- catch(FileNotFoundException e)
- {
- System.out.println(e);
- }
- catch(IOException e)
- {
- System.out.println(e);
- }
- }
- public static void readRectangle()
- {
- try(ObjectInputStream is =
- new ObjectInputStream(
- new FileInputStream("object.dat")))
- {
- Rectangle r = (Rectangle)is.readObject();
- System.out.println(r);
- System.out.println(is.readObject());
- System.out.println(is.readObject());
- // Testing
- r.setDimension(100, 20);
- System.out.println(r);
- System.out.println("End of readRectangle");
- }
- catch(FileNotFoundException e)
- {
- System.out.println(e);
- }
- catch(IOException | ClassNotFoundException e)
- {
- System.out.println(e);
- }
- }
- public static void saveRectangle()
- {
- try(ObjectOutputStream os =
- new ObjectOutputStream(
- new FileOutputStream("object.dat")))
- {
- os.writeObject(new Rectangle(10, 2));
- os.writeObject(new Rectangle(20, 4));
- os.writeObject(new Rectangle(30, 3));
- System.out.println("End of saveRectangle");
- }
- catch(FileNotFoundException e)
- {
- System.out.println(e);
- }
- catch(IOException e)
- {
- System.out.println(e);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement