55import java .io .File ;
66import java .io .FileInputStream ;
77import java .io .FileOutputStream ;
8+ import java .io .IOException ;
89import java .nio .charset .Charset ;
910import java .util .HashMap ;
1011
1112import static group25 .Utils .AnsiColors .RED ;
12-
13+ import group25 . Server . Common .*;
1314/**
1415 * Contains utils for creating XStream objects, writing java objects
1516 * to XML files and reading them from XML files.
@@ -27,36 +28,54 @@ public XMLPersistor(Class classToWrite) {
2728 xstream .allowTypes (new Class [] {
2829 HashMap .class ,
2930 String .class ,
30- classToWrite
31+ classToWrite ,
32+ Flight .class ,
33+ Room .class ,
34+ Car .class ,
35+ Customer .class ,
3136 });
3237 this .xstream = xstream ;
3338 }
3439
35- public boolean writeObject (Object obj , String filename ) {
36- String objAsXML = this . xstream . toXML ( obj ) ;
37-
40+ public boolean writeObject (Object obj , String filepath ) {
41+ FileOutputStream fos = null ;
42+ File dataFile = new File ( filepath );
3843 try {
39- FileOutputStream fos = new FileOutputStream (filename );
40- fos .write ("<?xml version=\" 1.0\" >\n " .getBytes ("UTF-8" )); // XStream doesn't do this for you
41- fos .write (objAsXML .getBytes ("UTF-8" ));
44+ dataFile .getParentFile ().mkdir ();
45+ dataFile .createNewFile ();
46+ String objAsXML = this .xstream .toXML (obj );
47+ fos = new FileOutputStream (dataFile );
48+ fos .write ("<?xml version=\" 1.0\" ?>\n " .getBytes ("UTF-8" )); // XStream doesn't do this for you
49+ byte [] bytes = objAsXML .getBytes ("UTF-8" );
50+ fos .write (bytes );
51+ System .out .println ("finished writing " + bytes );
4252 } catch (Exception e ) {
4353 System .out .println (RED .colorString ("XMLPersistor.writeObject() exception: " )+e .getMessage ());
4454 System .exit (1 );
55+ } finally {
56+ if (fos != null ) {
57+ try {
58+ fos .close ();
59+ } catch (IOException e ) {
60+ e .printStackTrace ();
61+ }
62+ }
4563 }
4664
4765 return true ;
4866 }
4967
50- public <T > T readObject (String filename ) {
68+ public <T > T readObject (String filepath ) {
5169 String str = null ;
5270
5371 try {
54- File file = new File (filename );
72+ File file = new File (filepath );
5573 FileInputStream fis = new FileInputStream (file );
5674 byte [] data = new byte [(int ) file .length ()];
5775
5876 fis .read (data );
5977 str = new String (data , "UTF-8" );
78+ System .out .println (str );
6079 } catch (Exception e ) {
6180 return null ; // file not found
6281 }
0 commit comments