views:

827

answers:

2

In java i would read the whole file in to byte array and do some processing with it. Now i want to implement the same algorithm in clojure.

What i am wondering is can i use a list instead of an array?

I know i can create array from clojure but what is the lisp way of handling this?

+7  A: 

If the file in question is very large, you should always consider using a memory mapped file. clojure.contrib.mmap offers some functions to deal with that.

I know i can create array from clojure but what is the lisp way of handling this?

I don't know about the Lisp way, but the Clojure way allows you to use the sequence functions on arrays, so you don't have to decide between efficient representation and comfortable handling (which in my opinion is one of the points that makes Clojure so pragmatic).

pmf
Files i am going to read are small. 200-300 Kb's max.
Hamza Yerlikaya
Then just create the array as you would in Java and use Clojure's functions that accept a seqable, which magically work with arrays. For any further advise, you could mention what exactly you need to do with the content. Since you're using a byte array, I'm assuming you need to do binary stuff, in which case you might want to read the following article, which illustrates some nice patterns to use: http://gnuvince.wordpress.com/2009/01/29/reading-binary-data-in-clojure/
pmf
A: 

here is a lazy sequence of the bytes in the file and closes the file handle when the last byte has been read. If you work with sequences fed by huge files be careful not to hold onto the head of the sequence anywhere or you will run out of memory. It's ok to hold onto the file handle though in case you need to manually close it in an error condition.

(defn byte-seq [rdr]
  (let [result (. rdr read)]
    (if (= result -1)
      (do (. rdr close) nil)
      (lazy-seq (cons result (byte-seq rdr))))))
Arthur Ulfeldt