Reputation: 29
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.
Upvotes: 0
Views: 213
Reputation: 92117
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."))
Upvotes: 1
Reputation: 29984
If you really need to write to the file system, a handy way is to use java.io.File/createTempFile
. See
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/File.html
Another, easier option is to use tupelo.string/string->stream
from the Tupelo Library. It was built for just this purpose:
(ns tst.demo.core
(:use demo.core tupelo.core tupelo.test)
(:require
[tupelo.core :as t]
[tupelo.string :as ts] ))
(dotest
(is= "Hello World!"
(slurp
(ts/string->stream "Hello World!"))) )
Add the following to your project.clj
file:
[tupelo "0.9.152"]
Upvotes: 0