On Nov 23, 6:35 pm, Parth Malwankar <[EMAIL PROTECTED]> wrote:
> I am trying to translate the following Java
> snippet into a file copy routine in Clojure.
>
> public static void copy(InputStream in, OutputStream out) throws
> IOException {
> byte[] buffer = new byte[1024];
> while (true) {
> int bytesRead = in.read(buffer);
> if (bytesRead == -1) break;
> out.write(buffer, 0, bytesRead);
> }
> }
I wrote a stream copying function for my web framework, Compojure.
Here's my version:
(defn pipe-stream
"Pipe the contents of an InputStream into an OutputStream."
([in out]
(pipe-stream in out 4096))
([#^InputStream in #^OutputStream out bufsize]
(let [buffer (make-array (. Byte TYPE) bufsize)]
(loop [len (. in (read buffer))]
(when (pos? len)
(. out (write buffer 0 len))
(recur (. in (read buffer))))))))
It uses a loop/recur to replace the while loop. Actually, looking at
that code now, it seems a little old. You could probably cut down on a
few parethesis by replacing (. Byte TYPE) for Byte/TYPE and (. in
(read buffer)) to (.read in buffer). However, aside from minor syntax
improvements, that should do the job.
- James
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To post to this group, send email to clojure@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---