Mercurial > hg > jslab
view src/samer/core_/Saver.java @ 0:bf79fb79ee13
Initial Mercurial check in.
author | samer |
---|---|
date | Tue, 17 Jan 2012 17:50:20 +0000 |
parents | |
children |
line wrap: on
line source
package samer.core; import samer.core.types.*; import java.io.*; /** An Agent that manages saving and loading of a Saveable object */ public class Saver implements Agent { Saveable obj; VFile file, txtfile; public Saver(Saveable obj) { init(obj); } public Saver(Saveable obj, Node node) { Shell.push(node); init(obj); Shell.pop(); } public void setName(String n) { file.setFile(new File(n)); } public File getFile() { return file.getFile(); } private void init(Saveable obj) { this.obj=obj; file = new VFile("file","",0); txtfile = new VFile("text file","",0); } public void load() throws Exception { Shell.print("loading "+obj+" from "+file); FileInputStream f=new FileInputStream(file.getFile()); try { obj.load(new BufferedInputStream(f)); } finally { f.close(); } } public void save() throws Exception { Shell.print("saving "+obj+" to "+file); OutputStream f=new BufferedOutputStream( new FileOutputStream(file.getFile())); try { obj.save(f); } finally { f.close(); } } public void read() throws Exception { Shell.print("loading "+obj+" as text from "+txtfile); FileReader f=new FileReader(txtfile.getFile()); try { obj.read(f); } finally { f.close(); } } public void write() throws Exception { Shell.print("saving "+obj+" as text to "+txtfile); Writer w=new BufferedWriter(new FileWriter(txtfile.getFile())); try { obj.write(w); } finally { w.close(); } } public void getCommands(Registry r) { r.add("load").add("load text"); r.group(); r.add("save as").add("save").add("save text"); } public void execute(String cmd, Environment env) throws Exception { if (cmd.equals("load")) { try { env.datum().get(file); load(); } catch (Exception x) { Shell.print("Error loading: "+x); } } else if (cmd.equals("save as")) { try { env.datum().get(file); txtfile.decode(file.string()+".txt"); save(); } catch (Exception x) { Shell.print("Error saving: "+x); } } else if (cmd.equals("save")) { try { save(); } catch (Exception x) { Shell.print("Error saving: "+x); } } else if (cmd.equals("load text")) { try { env.datum().get(txtfile); read(); } catch (Exception x) { Shell.print("Error reading: "+x); } } else if (cmd.equals("save text")) { try { env.datum().get(txtfile); write(); } catch (Exception x) { Shell.print("Error writing: "+x); } } } }