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: The slurp method 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 slurp method that contains the contents of file.txt file.

Note: We have the main.clj, which is our code, and the file.txt, which is the file we are reading from.

  • Line 8: We call the function func.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved