liveBook · Manning

Clojure.java.io

As explained in Clojure: The Essential Reference

clojure.java.io is a Clojure namespace that provides polymorphic utilities for interacting with Java input/output resources, files, URLs, and classpath resources.

`clojure.java.io` provides Clojure-friendly functions for Java input and output. Rather than replacing Java IO, it smooths over differences among streams, readers, writers, files, URLs, and classpath resources. Require it as `(require '[clojure.java.io :as io])`. section 22.8

Choose a function by the kind of IO object or resource you need:

  • `io/reader` and `io/writer` produce buffered readers and writers; `io/input-stream` and `io/output-stream` produce streams. They accept several kinds of input, reducing the need to assemble Java adapters yourself. section 22.8
  • `io/resource` locates a classpath resource. `io/file` and `io/as-url` convert supported values into Java files and URLs; their coercion behavior can be extended. section 22.8
  • `io/copy`, `io/make-parents`, and `io/delete-file` handle common file tasks. Their arguments and failure behavior still matter: deleting a missing file normally throws an `IOException`. section 22.8

Read lines and close the reader

`(with-open [r (io/reader "/usr/share/dict/words")] (count (line-seq r)))` returns `235886` for the file shown. Keep work that consumes the line sequence inside `with-open`: IO objects hold resources that need closing. section 22.8

Distinguish content from a location

`io/reader` treats a string as a location, not as the text to read. For an in-memory string `s`, use `(with-open [r (io/reader (char-array s))] (slurp r))`; the result is the contents of `s`. section 22.8

Writer options include `:encoding` and `:append`. For file operations, check the demonstrated contracts rather than assuming every pair of inputs works: `(io/copy "/usr/share/dict/words" (io/file "/tmp/words2"))` returns `nil`, while string-to-string copying requires the illustrated custom `do-copy` method. section 22.8

How Clojure: The Essential Reference covers it

How deep it goes
Explains return types, accepted inputs, resource closing, coercion extension, and selected file-operation edge cases.
Examples
Uses dictionary-file line counts, in-memory string reading, file copying, and deletion of a missing file.
What it assumes
Assumes familiarity with Clojure forms and introduces the relevant Java IO abstractions through their functions and return types.
What you can do after
Apply it via `clojure.java.io` to open and close readers, convert resources, and perform common file operations.
How it connects
Connects Java streams, readers, writers, classpath resources, URLs, file operations, and protocols.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.