Search code examples
clojureio

In Clojure, instead of providing a path, I want to use a string with the contents of a file


I'm currently writing a restful API and need to receive whole files as string. I didn't write the actual functions which parse those files and must somehow feed these strings into functions which except a path.

So, what I want to find/build is a function which would solve this Problem:

(slurp (INSERT-MAGIC-HERE "The content of my file."))

EDIT:

While both answers seemed to work, the most reliable thing I found was to use "char-array". This prevents any error about the stream being closed which I got quite often.


Solution

  • slurp uses a very flexible mechanism to figure out how to understand its input arguments: it certainly doesn't insist that they be a file. For example, it will accept a java.io.Reader. And it is easy to build a Reader from a String, simply by constructing a StringReader. So,

    (slurp (java.io.StringReader. "The content of my file."))