Sunday, October 25, 2015

Simple Java Serialization

// this is a very simple example of java serialization example
//Serializations: Assume this is my class to be serialized
import java.util.ArrayList;

public class Dish {
private String dishName;
private ArrayList<String> ingredient;

public String getDishName(){
return this.className;
}
public ArrayList<String> getIngredient(){
return this.variableNames;
}
public void setDishName(String dishName){
this.dishName = dishName;
}
public void setIngredient(ArrayList<String> ingredient){
this.ingredient = ingredient;
}
}

// This class will read and write. I reused the one found here which is awesome.
// Thanks Awesome person who did this
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
public class Builder {
    public static void writeXML(Schema f, String filename) throws Exception{
        XMLEncoder encoder =
           new XMLEncoder(
              new BufferedOutputStream(
                new FileOutputStream(filename)));
        encoder.writeObject(f);
        encoder.close();
    }

    public static Schema readXML(String filename) throws Exception {
        XMLDecoder decoder =
            new XMLDecoder(new BufferedInputStream(
                new FileInputStream(filename)));
        Schema o = (Schema)decoder.readObject();
        decoder.close();
        return o;
    }
}

// This is a class using both
public class Food {
    public static void main(String[] args) {
        String filename = "/home/...../Dishes.xml";
        String name = "Pizza";
        ArrayList<String>  ingredients= new ArrayList<String>();
        vars.add("dough");
        vars.add("cheese");
        vars.add("sauce");

        Schema s = new Schema();
        s.setDishName(name);
        s.setIngredient(ingredients);

         try { Builder.writeXML(s, filename);  }
            catch (Exception ex){ System.out.println(ex); }
         try {
         Schema s2 = Builder.readXML(filename);
         System.out.println(s2.getDishName());
         System.out.println(s2.getIngredient().toString());
         } catch (Exception ex){ System.out.println(ex); }
    }

}//Food


// Java read from a file and return the string
public static String readFile(String fileName){

try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {

String content = "";

String line = null;
   while ((line = reader.readLine()) != null) {
       content = content + line;
   }
   reader.close();
 
   return content;
 
} catch (IOException x) {
   System.err.format("IOException: %s%n", x);
   return null;
}

}