How to read from a file in Clojure
Overview
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.
Syntax
slurp filename
Syntax of the slurp method in Clojure
Parameter
filename: Theslurpmethod receives a single parameter which is the file name.
Return value
The slurp method returns a string from a file.
Example
main.clj
file.txt
(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)
Explanation
The above code example illustrates how we use the slurp method to read a text file.
- Line 3: We declare a function
func. - Line 4: We print the string returned by
slurpmethod that contains the contents offile.txtfile.
Note: We have the
main.clj, which is our code, and thefile.txt, which is the file we are reading from.
- Line 8: We call the function
func.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved