/* * Copyright (C) 2007-2013 Xagasoft, All rights reserved. * * This file is part of the libgats library and is released under the * terms of the license contained in the file LICENSE. */ import com.xagasoft.gats.*; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * This simple example class shows several ways of constructing a Gats object * hierarchy and also how to write and read Gats packets to and from streams. */ class FileExample { public static void writeFile() { System.out.println(); System.out.println("Creating a new gats object tree..."); GatsDictionary root = new GatsDictionary(); // Automatically determine the type of Gats object and insert it // for you root.put("String", "This is a string"); root.put("Integer", 445 ); root.put("Float", 44.5 ); root.put("Boolean", true ); // Ensure the correct type and insert it yourself root.put("ExplicitFloat", new GatsFloat( 44 ) ); GatsList lst = new GatsList(); lst.add( new GatsString("Hello") ); lst.add( new GatsInteger( 314159 ) ); lst.add( new GatsFloat( 3.14159 ) ); root.put("List", lst ); GatsDictionary subDict = new GatsDictionary(); subDict.put("name", "Bob"); root.put("Dictionary", subDict ); try { System.out.println("Writing tree to file: test.gats"); FileOutputStream fos = new FileOutputStream("test.gats"); GatsOutputStream gos = new GatsOutputStream( fos ); int iBytes = gos.writeObject( root ); System.out.println("Wrote " + iBytes + " total bytes."); } catch( FileNotFoundException e ) { System.out.println("Error opening file."); } catch( IOException e ) { System.out.println("Error writing data."); } } public static void readFile() { System.out.println(); try { System.out.println("Reading in gats file: test.gats"); FileInputStream fis = new FileInputStream("test.gats"); GatsInputStream gis = new GatsInputStream( fis ); GatsObject obj = gis.readObject(); System.out.println("Full object: " + obj ); GatsDictionary root = (GatsDictionary)obj; System.out.println("An integer: " + root.getInt("Integer") ); // This is a little akward since getString returns a byte array, // so if you want to use the data as a java string you have to build // the string object yourself. System.out.println("Sub string: " + new String( root.getDict("Dictionary").getString("name") ) ); root.get("aoeu"); root.getDict("aoeu"); root.getList("aoeu"); root.getInt("aoeu"); root.getFloat("aoeu"); root.getBool("aoeu"); root.getString("aoeu"); } catch( FileNotFoundException e ) { System.out.println("Error opening file."); } catch( IOException e ) { System.out.println("Error reading data."); } catch( KeyNotFoundException e ) { System.out.println("Key not found."); } } public static void main( String args[] ) { System.out.println("GATS file example."); writeFile(); readFile(); } }