liveBook · Manning

Clojure.java.io/as-url

As explained in Clojure: The Essential Reference

clojure.java.io/as-url is a Clojure function that converts supported location representations into URL objects.

clojure.java.io/as-url converts a location representation into a Java URL object, avoiding direct java.net.URL construction. String locations may identify classpath resources, local files, or protocols such as http. section 22.8

Equivalent file URLs

A string and a java.io.File can produce equivalent URLs. A java.nio.file.Path must first be converted with toUri unless Coercions is extended: (def u1 (as-url "file:///tmp/words")) (def u2 (as-url (file "/tmp/words"))) (= u1 u2) ;; true section 22.8

(require '[clojure.java.io :refer [as-url file]])
(import 'java.nio.file.FileSystems)

(def path ; #1
  (.. FileSystems
      getDefault
      (getPath "/tmp" (into-array String ["words"]))
      toUri))

(def u1 (as-url "file:///tmp/words")) ; #2
(def u2 (as-url (file "/tmp/words"))) ; #3
(def u3 (as-url path))                ; #4

(= u1 u2 u3) ; #5
;; true

Compare URL creation from a string, java.io.File, and a Path-derived URI. section 22.8

How Clojure: The Essential Reference covers it

How deep it goes
Defines supported representations and demonstrates polymorphism, but stops short of directly coercing java.nio.file.Path values.
Examples
Uses file URL strings, java.io.File values, Path-derived URIs, and an optional Coercions extension.
What it assumes
Assumes familiarity with Clojure namespaces and basic Java URL, URI, File, and Path types.
What you can do after
Apply it to create URL objects from common location values and adapt unsupported Path values through toUri.
How it connects
Connects URL conversion with URI, classpath resources, java.io.File, java.nio.file.Path, and Coercions.

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.