如何在Clojure特定目录中的所有文件中创建列表?我必须诉诸Java还是Clojure可以本地处理?
Clojure设计为包含Java平台,这是Clojure不提供自己的API的领域。这意味着您可能必须学习Java,但是必须直接从Clojure完全使用要使用的类。
您应该在javadocs中阅读的一个类是(def directory (clojure.java.io/file "/path/to/directory"))
(def files (file-seq directory))
(take 10 files)
,它表示文件路径。
java.io.File
http://docs.oracle.com/javase/6/docs/api/java/io/File.html实例方法返回.listFiles
对象的数组(您可以将其用作序列)–由File
实例标识的目录中的每个条目一个。还有其他一些有用的方法可以确定File
是否存在,是否为目录等。
File
(ns my-file-utils
(:import java.io.File))
(defn my-ls [d]
(println "Files in " (.getName d))
(doseq [f (.listFiles d)]
(if (.isDirectory f)
(print "d ")
(print "- "))
(println (.getName f))))
;; Usage: (my-ls (File. "."))
的构造函数有时使用起来有点不方便(尤其是一次性合并多个路径段时),在这种情况下,Clojure提供了有用的帮助函数:File
。作为参数,它接受路径段作为字符串或文件。段与平台的正确路径分隔符相连。
clojure.java.io/file
注意:Clojure还提供了http://clojuredocs.org/clojure_core/clojure.java.io/file函数,该函数通过从给定文件开始的文件层次结构返回预定的遍历(作为seq)。
也请检查file-seq
。
如果只需要目录中的文件列表,则可能不值得引入额外的依赖关系,但是那里有许多有用的实用程序功能,例如:
fs library
后一个表达式是从方法listFiles返回的文件对象数组,该方法在从路径“ / tmp”创建的文件对象上调用。这是一种奇特的写法:
(use 'clojure.java.io)
(-> "/tmp" file .listFiles)
通常,当我们说要列出目录时,是指我们要获取文件名或路径,所以->
列出目录的最简单方法:
(.listFiles (file "/tmp"))
如果您要递归列出,则:
(seq (.list (clojure.java.io/file ".")))
要使修改后的代码与原始示例代码的功能匹配,您应该添加调用以获取文件名,就像这样。
(map #(.getPath %)
(file-seq (clojure.java.io/file ".")))
宏,用于以递归方式或仅在父目录中列出目录中的文件。它还可以搜索带有特定结尾扩展名的文件。
(def directory (clojure.java.io/file "/path/to/directory"))
(def files
(for [file (file-seq directory)] (.getName file)))
(take 10 files)
它导致不同的功能,可以通过目录调用该功能以递归或非递归的方式获取文件列表,目录或匹配的扩展文件。示例是-
;; lists all the files recursively inside the directory passed as d like "."
(defmacro my-rec-list
"generate the recursive list" {:added "1.0"}
[d str rec]
`(->> ~d
clojure.java.io/file
~(if (= rec "rec")
`file-seq
`(.listFiles))
~(cond
(= str "file") `(filter #(.isFile %))
(= str "dir") `(filter #(.isDirectory %))
:always `(filter #(.matches (.getPathMatcher
(java.nio.file.FileSystems/getDefault)
~str) (.getFileName (.toPath %)))))
(mapv #(.getAbsolutePath %))))
(defn my-rec-ls-file
"generate the recursive list for only files in a directory"
[d ]
(my-rec-list d "file" "rec"))
(defn my-rec-ls-dir
"generate the recursive list for only directory"
[d ]
(my-rec-list d "dir" "rec"))
(defn my-rec-ls-jpg
"generate the recursive list for files and directory"
[d ]
(my-rec-list d "glob:*.jpg" "rec"))
(defn my-ls-file
"generate the recursive list for only files in a directory"
[d ]
(my-rec-list d "file" "norec"))
(defn my-ls-dir
"generate the recursive list for only directory"
[d ]
(my-rec-list d "dir" "norec"))
(defn my-ls-jpg
"generate the recursive list for files and directory"
[d ]
(my-rec-list d "glob:*.jpg" "norec"))