de-narm
de-narm

Reputation: 29

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.

Upvotes: 0

Views: 213

Answers (2)

amalloy
amalloy

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

Alan Thompson
Alan Thompson

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

Related Questions