-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.clj
58 lines (52 loc) · 1.67 KB
/
io.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
(ns ring.util.io
"Utility functions for handling I/O."
{:author "James Reeves"
:contributors "Modified by Carlos da Cunha Fontes to work with Babashka"
:url "https://github.com/ring-clojure/ring"
:license {:name "Distributed under the MIT License, the same as Ring."}}
(:import [java.io PipedInputStream
PipedOutputStream
ByteArrayInputStream
File
IOException]))
(defn piped-input-stream
"Create an input stream from a function that takes an output stream as its
argument. The function will be executed in a separate thread. The stream
will be automatically closed after the function finishes.
For example:
(piped-input-stream
(fn [ostream]
(spit ostream \"Hello\")))"
{:added "1.1"}
[func]
(let [input (PipedInputStream.)
output (PipedOutputStream.)]
(.connect input output)
(future
(try
(func output)
(finally (.close output))))
input))
(defn string-input-stream
"Returns a ByteArrayInputStream for the given String."
{:added "1.1"}
([^String s]
(ByteArrayInputStream. (.getBytes s)))
([^String s ^String encoding]
(ByteArrayInputStream. (.getBytes s encoding))))
(defn close!
"Ensure a stream is closed, swallowing any exceptions."
{:added "1.2"}
[stream]
(when (instance? java.io.Closeable stream)
(try
(.close ^java.io.Closeable stream)
(catch IOException _ nil))))
(defn last-modified-date
"Returns the last modified date for a file, rounded down to the nearest
second."
{:added "1.2"}
[^File file]
(-> (.lastModified file)
(/ 1000) (long) (* 1000)
(java.util.Date.)))