Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

clojure

How to read from a file in Clojure

Chinweuba Elijah Azubuike

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
Hello from Educative..
Example of the usage of the slurp method

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 define a variable file1, and then we use the slurp method on the 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 5: We use the println method to print out the string returned by the slurp method.
  • Line 6: We call the function func.

RELATED TAGS

clojure

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring