Most times we want to work with an external file, especially when it involves reading text. So, let's learn how to read a file in Clojure. We will be making use of the slurp
method. The slurp
method is used to read a file.
slurp filename
filename
: The slurp
method receives a single parameter which is the file name.The slurp
method returns a string from a file.
(ns clojure.examples.hello(:gen-class))(defn func [](println (slurp "file.txt");; (let [file1 (slurp "file.txt")] (println file1));; we can store the string in a variable as well)(func)
The above code example illustrates how we use the slurp
method to read a text file.
func
.slurp
method that contains the contents of file.txt
file. Note: We have the
main.clj
, which is our code, and thefile.txt
, which is the file we are reading from.
func
.Free Resources