Skip to content

Programming · Games · Life outdoors

File Dialogs in Clojure

(See my full list of Clojure Swing examples and tutorials at Clojure Swing Interop)

When dealing with files, its very handy to use file dialogs. Here’s a quick example of using a JFileChooser  to select a file to slurp  and print.

Note the use of  (into-array [“txt”]) as an argument to the FileNameExtensionFilter constructor. This is because the file extensions are provided as a String...  meaning a java.lang.String  array.

Also note, the .showOpenDialog  call uses nil  instead of a JFrame . We do that because we don’t have a JFrame  showing that we want to associate the file dialog with.

(ns swingproject.core
(:gen-class)
(:import
[javax.swing SwingUtilities JFileChooser]
[ javax.swing.filechooser FileNameExtensionFilter]))
(defn slurp-file [java-file-object]
(let [contents (slurp java-file-object)]
(println contents)))
(defn slurp-a-thon
[]
;; opening and using a file dialog
(SwingUtilities/invokeLater
#(let [my-filter (FileNameExtensionFilter.
"Text file to slurp"
(into-array ["txt"]))
my-file-chooser (doto (JFileChooser.)
(.setFileFilter my-filter))
selection-option (.showOpenDialog my-file-chooser nil)
selection-file (.getSelectedFile my-file-chooser )
]
(if (= selection-option JFileChooser/APPROVE_OPTION)
(future (slurp-file selection-file)))))
;;giving the program some time to print before exiting
(Thread/sleep 60000)
(System/exit 0))
(defn -main
"entry point for app"
[& args]
(slurp-a-thon))