/*
 *
 * FileOutputDemo
 *
 * Demonstration of FileOutputStream and
 * PrintStream classes
 *
 */

import java.io.*;

public class SaveXMLfile
{

	public static void save(Table tab, File filename)
	{
		FileOutputStream out; /* declare a file output object */
		PrintStream p; /* declare a print stream object */

		try
		{
				/* Create a new file output stream connected to "myfile.txt" */
				out = new FileOutputStream(filename);

				/* Connect print stream to the output stream */
				p = new PrintStream( out );

				p.println ("<TABLE>");

				/* extract the column information belonging to the table */
				p.println ("<META_DATA>");
				Column col = tab.getCol();
				String[] colnames = col.getColNames();
				int[] coltypes = col.getColTypes();

				/* insert the no. of columns */
				p.println ("<NUMBER_OF_ROWS>");
				p.println (tab.getNoRowSet());
				p.println ("</NUMBER_OF_ROWS>");
				p.println ("<NUMBER_OF_COLS>");
				p.println (col.getColNumber());
				p.println ("</NUMBER_OF_COLS>");
				/* insert the column names and their types */
				p.println ("<Column_Data>");
				for (int i=0; i<colnames.length; i++) 
				{
					p.println ("<Column>");
					p.println ("<Name>");
					p.println (colnames[i]);
					p.println ("</Name>");
					p.println ("<Type>");
					p.println (coltypes[i]);
					p.println ("</Type>");
					p.println ("</Column>");
				}
				p.println ("</Column_Data>");
				p.println ("</META_DATA>");

				/* Extract the row information belonging to the table */
				p.println ("<ROW_DATA>");
				for (int j=0; j<tab.getNoRowSet(); j++) /* go through each row */
				{
					Row r = (Row) tab.getRow(j) ;
					p.println ("<ROW>");
					Object[] rowVals = r.getRowValues();
					for (int k=0; k<rowVals.length; k++) /* go through each object in the row */
					{
						 p.println ("<CELL>");
						 p.println(rowVals[k]);
						 p.println ("</CELL>");
					}
					/* place the start and end time */
					p.println ("<START_TIME>");
					p.println (r.getRow_st());
					p.println ("</START_TIME>");
					p.println ("<END_TIME>");
					p.println (r.getRow_et());
					p.println ("</END_TIME>");
					p.println ("</ROW>");
			   }
				p.println ("</ROW_DATA>");

				p.println ("</TABLE>"); /* mark end of table */
				p.close();
		}

		catch (Exception e)
		{
				System.err.println ("Error writing to file");
		}
	}
}

