Reputation: 47
I am a newbie to Clojure and I am trying to read a file which should be specified at the command line.
When I try the following, giving the file name at REPL, it is working
(ns testpj.core
(:require [clojure.java.io :as io]))
(defn readfile [filename]
(println (System/getProperty "user.dir"))
(println "Arguments: " filename)
(slurp filename))
And then I run this at REPL and I get the contents of the file
(require '[testpj.core :as h])
(h/readfile file1.txt)
But when I change the above code to main and I try to give the file name at the command line
lein run file1.txt
(defn -main [& args]
(println (System/getProperty "user.dir"))
(println "Arguments: " args)
(slurp args))
, I am getting the following error:
"java.lang.IllegalArgumentException: Cannot open <("file1.txt")> as an InputStream."
Can anyone help? Thanks
Upvotes: 3
Views: 1199
Reputation: 4806
The argument vector for -main
is [& args]
, which means that -main
accepts any number of arguments. Inside the function, the var args
will be bound to a list of the arguments passed to it, or nil
if no arguments are given to the function. So, to slurp
the first argument passed to a function which takes multiple arguments:
(slurp (first args))
Upvotes: 3