Created
October 20, 2012 14:31
-
-
Save ponkore/3923420 to your computer and use it in GitHub Desktop.
Clojure でディレクトリにあるファイルの扱い
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
user=> (import 'java.io.File) | |
user=> (File. ".") | |
#<File .> | |
user=> (def curdir (File. ".")) | |
#'user/curdir | |
user=> curdir | |
#<File .> | |
user=> (.list curdir) | |
#<String[] [Ljava.lang.String;@33d6798> | |
user=> (seq (.list curdir)) | |
(".bash_history" ".bash_profile" ... ) | |
user=> (defn dir? [f] (.isDirectory f)) | |
user=> (defn fname [f] (.getName f)) | |
user=> (filter dir? (.listFiles curdir)) | |
(#<File ./.cache> ... ) | |
user=> (map fname (filter dir? (.listFiles curdir))) | |
(".cache" ".ccl" ... ) | |
user=> (map fname (filter (complement dir?) (.listFiles curdir))) | |
(".bash_history" ".bash_profile" ... ) | |
user=> (defn subdirs [dir] (.listFiles dir)) | |
user=> (tree-seq dir? subdirs (File. "work/lisp")) | |
(#<File ./work/lisp> #<File ./work/lisp/alexandria> #<File ./work/lisp/alexandria/.boring> ... ) | |
user=> (defn fullpath [f] (.getAbsolutePath f)) | |
user=> (map fullpath (tree-seq dir? subdirs (File. "work/lisp"))) | |
("/Users/masao/work/lisp" "/Users/masao/work/lisp/alexandria" ... ) | |
user=> (defn filter-func [f] (empty? (re-find #"\.git" (fname f)))) | |
user=> (filter filter-func (tree-seq has-subdir? subdirs (File. "work/lisp"))) | |
(#<File work/lisp> #<File work/lisp/alexandria> #<File work/lisp/alexandria/.boring> ... ) | |
user=> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(import 'java.io.File) | |
(defn fname [f] (.getName f)) | |
(defn dir? [f] (.isDirectory f)) | |
(defn dirtree-seq | |
[rootdir] | |
"" | |
(let [dirtree-contains? (fn [f] (empty? (re-find #"\.git" (fname f)))) | |
has-subdir? (fn [f] (and (dir? f) (dirtree-contains? f))) | |
subdirs (fn [f] (.listFiles f))] | |
(->> rootdir | |
(File.) | |
(tree-seq has-subdir? subdirs) | |
(filter dirtree-contains?)))) | |
(defn fullpath [f] (.getAbsolutePath f)) | |
(doseq [s (map fullpath (dirtree-seq "work/lisp"))] | |
(println s)) | |
;;; ちなみに file-seq は、無視する subdirectory のパターンを指定できない。 | |
#_(defn file-seq | |
"A tree seq on java.io.Files" | |
{:added "1.0" | |
:static true} | |
[dir] | |
(tree-seq | |
(fn [^java.io.File f] (. f (isDirectory))) | |
(fn [^java.io.File d] (seq (. d (listFiles)))) | |
dir)) | |
(use 'clojure.java.io) | |
(line-seq (reader ".bashrc")) | |
(with-open [rdr (reader ".bashrc")] | |
(doall (line-seq rdr))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment