import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Random;


public class DemoObjectIO {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		
//		TestClass [] td  = new TestClass[10];
//		Random r = new Random();
//	
//		for(int i=0; i < td.length; i++)
//			td[i] = new TestClass(r.nextInt(), r.nextFloat(), r.nextDouble(), "Name"+r.nextInt(100));
//		
//		System.out.println("Before save...");
//		printObjects(td);
//		
//		saveObjects(td);
		
		TestClass [] input = readObjects();
		
		System.out.println("After save...");
		 printObjects(input);
	}

	private static void printObjects(TestClass[] td) {
		for(TestClass tc: td) 
			System.out.println(tc);
	}

	private static TestClass [] readObjects() {
		File infile;
		
		infile = new File("resources/objectFile.obj");
		TestClass [] inputData = null;
		
		FileInputStream fis;
		try {
			fis = new FileInputStream(infile);
			ObjectInputStream ois = new ObjectInputStream(fis);
			
			//read object from object input stream
			Object o = ois.readObject();
			
			//cast object correctly
			inputData = (TestClass []) o;
		} catch (FileNotFoundException e) {
			System.out.println("File not found");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("Problems reading file");
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.out.println("Class information not found");
			e.printStackTrace();
		}
		
		
		return inputData;
	}

	private static void saveObjects(TestClass [] data) {
		File outfile;
		
			
		outfile = new File("resources/objectFile.obj");
		
		try {
			FileOutputStream fos = new FileOutputStream(outfile);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			
			//write object (i.e. state of object) to object output stream
			oos.writeObject(data);
		} catch (FileNotFoundException e) {
			System.out.println("File not found");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("Problems writing file!");
			e.printStackTrace();
		}
		
	}
}
