Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 13th, 2011  |  syntax: Clojure  |  size: 0.98 KB  |  hits: 155  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. (defn create-object-output-stream
  2.   [filename]
  3.   (if (file-exists? filename)
  4.     (-> filename (FileOutputStream. true) AppendingObjectOutputStream.)
  5.     (-> filename (FileOutputStream. true) ObjectOutputStream.)))
  6.  
  7. (defn write-to-file
  8.   [file-key, data-map]    
  9.   (with-open [obj-out (-> file-key determine-filename create-object-output-stream)]
  10.     (try
  11.       (.writeObject obj-out, (replace-functions-by-symbols data-map))
  12.       (.flush obj-out)
  13.       (catch Throwable t
  14.         (debug-repl "write-to-file")))))
  15.  
  16.  
  17. (defn read-from-file
  18.   [file-key]
  19.   (let [filename (determine-filename file-key)]
  20.     (with-open [obj-in (-> filename FileInputStream. ObjectInputStream.)]
  21.       (loop [result (transient [])]
  22.         (try
  23.           (let [obj (.readObject obj-in)]
  24.             (recur (conj! result obj)))  
  25.           (catch EOFException eof
  26.             (persistent! result))
  27.           (catch Throwable t
  28.             (println t)
  29.             (debug-repl "read-from-file")))))))