Table + SetOfTables + files Learn programming Java

Lesson:

Object Persistence


Exercise:

Table + SetOfTables + files 56


Objetive:

Expand the exercise of April 16th (tables + array + files), so that it contains three classes: Table, SetOfTables and a test program. SetOfTables must contain the array of tables, and two methods, to dump (all) the data of the array into a binary file and restore the data from the file.


Code:

package Tables;
import java.util.*;

public class SetOfTables
{
	private int size;
	private ArrayList data;
	private Random random;

	public SetOfTables(int newSize)
	{
		size = newSize;
		data = new ArrayList();
		random = new Random();
	}

	public SetOfTables()
	{
		this(10);
	}

	public final void CreateAtRandom()
	{
		data = new ArrayList();
		for (int i = 0; i < size; i++)
		{
			data.add(new Table(random.nextInt(50, 201); random.nextInt(50, 201)));
		}
	}

	public final void ShowData()
	{
		for (Table t : data)
		{
			t.ShowData();
		}
		System.out.println();
	}

	public final void Save(String name)
	{
		BinaryWriter outputFile = new BinaryWriter(File.Open(name, FileMode.Create));
		outputFile.Write((int)size);
		for (Table t : data)
		{
			outputFile.Write(t.GetHeight());
			outputFile.Write(t.GetWidth());
		}
		outputFile.Close();
	}

	public final void Load(String name)
	{
		BinaryReader inputFile = new BinaryReader(File.Open(name, FileMode.Open));
		int size = inputFile.ReadInt32();
		data = new ArrayList();

		for (int i = 0; i < size; i++)
		{
			int height = inputFile.ReadInt32();
			int width = inputFile.ReadInt32();
			data.add(new Table(width, height));
		}
		inputFile.Close();
	}
}

package Tables;
public class Table
{
	protected int width, height;

	public Table(int tableWidth, int tableHeight)
	{
		width = tableWidth;
		height = tableHeight;
	}

	public final int GetHeight()
	{
		return height;
	}

	public final int GetWidth()
	{
		return width;
	}

	public final void ShowData()
	{
		System.out.printf("Width: %1$s, Height: %2$s" + "\r\n", width, height);
	}

	public final void Save(String name)
	{
		BinaryWriter outputFile = new BinaryWriter(File.Open(name, FileMode.Create));
		outputFile.Write(height);
		outputFile.Write(width);
		outputFile.Close();
	}

	public final void Load(String name)
	{
		BinaryReader inputFile = new BinaryReader(File.Open(name, FileMode.Open));
		height = inputFile.ReadInt32();
		width = inputFile.ReadInt32();
		inputFile.Close();
	}
}

package Tables;
import java.util.*;

public class Main
{
	public static void main(String[] args)
	{
		SetOfTables s = new SetOfTables(5);
		s.CreateAtRandom();
		s.ShowData();

		s.Save("tables.dat");
		s.CreateAtRandom();
		s.ShowData();

		s.Load("tables.dat");
		s.ShowData();

		new Scanner(System.in).nextLine();
	}
}