I want to zip a file in clojure and I can't find any libraries to do it.
Do you know a good way to zip a file or a folder in Clojure?
Must I use a java library?
There is a stock ZipOutputStream in Java which can be used from Clojure. I don't know whether there is a library somewhere. I use the plain Java functions with a small helper macro:
(defmacro ^:private with-entry
[zip entry-name & body]
`(let [^ZipOutputStream zip# ~zip]
(.putNextEntry zip# (ZipEntry. ~entry-name))
~#body
(flush)
(.closeEntry zip#)))
Obviously every ZIP entry describes a file.
(require '[clojure.java.io :as io])
(with-open [file (io/output-stream "foo.zip")
zip (ZipOutputStream. file)
wrt (io/writer zip)]
(binding [*out* wrt]
(doto zip
(with-entry "foo.txt"
(println "foo"))
(with-entry "bar/baz.txt"
(println "baz")))))
To zip a file you might want to do something like this:
(with-open [output (ZipOutputStream. (io/output-stream "foo.zip"))
input (io/input-stream "foo")]
(with-entry output "foo"
(io/copy input output)))
All compression and decompression of files can be done with a simple shell command which we can access through clojure.java.shell
Using the same method you can also compress and decompress any compression type you would usually from your terminal.
(use '[clojure.java.shell :only [sh]])
(defn unpack-resources [in out]
(clojure.java.shell/sh
"sh" "-c"
(str " unzip " in " -d " out)))
(defn pack-resources [in out]
(clojure.java.shell/sh
"sh" "-c"
(str " zip " in " -r " out)))
(unpack-resources "/path/to/my/zip/foo.zip"
"/path/to/store/unzipped/files")
(pack-resources "/path/to/store/archive/myZipArchiveName.zip"
"/path/to/my/file/myTextFile.csv")
You can import this (gzip) https://gist.github.com/bpsm/1858654
Its quite interesting.
Or more precisely, you can use this
(defn gzip
[input output & opts]
(with-open [output (-> output clojure.java.io/output-stream GZIPOutputStream.)]
(with-open [rdr (clojure.java.io/reader input)]
(doall (apply clojure.java.io/copy rdr output opts)))))
You can use rtcritical/clj-ant-tasks library that wraps Apache Ant, and zip with a single command.
Add library dependency [rtcritical/clj-ant-tasks "1.0.1"]
(require '[rtcritical.clj-ant-tasks :refer [run-ant-task]])
To zip a file:
(run-ant-task :zip {:destfile "/tmp/file-zipped.zip"
:basedir "/tmp"
:includes "file-to-zip"})
Note: run-ant-task(s) functions in this library namespace can be used to run any other Apache Ant task(s) as well.
For more information, see https://github.com/rtcritical/clj-ant-tasks
Related
I have a method for zipping:
(defn zip-project [project-id notebooks files]
(with-open [out (ByteArrayOutputStream.)
zip (ZipOutputStream. out)]
(doseq [nb notebooks]
(.putNextEntry zip (ZipEntry. (str "Notebooks/" (:notebook/name nb) ".bkr")))
(let [nb-json (:notebook/contents nb)
bytes (.getBytes nb-json)]
(.write zip bytes))
(.closeEntry zip))
(doseq [{:keys [name content]} files]
(.putNextEntry zip (ZipEntry. (str "Files/" name)))
(io/copy content zip)
(.closeEntry zip))
(.finish zip)
(.toByteArray out)))
after I make a zip I want to save it into the file something like /tmp/sample/sample.zip, but I cannot seem to make it. here is what I am doing:
(defn create-file! [path zip]
(let [f (io/file path)]
(io/make-parents f)
(io/copy zip f)
true))
The problem is, when I run unzip from terminal it says that zip file is empty and if I unzip it using Archive utility it extracts with cpgz extension.
What am I doing wrong here?
You will need essentially 4 things
Import everything (normally you would use (ns ...) but you can run this in the repl
(import 'java.io.FileOutputStream)
(import 'java.io.BufferedOutputStream)
(import 'java.io.ZipOutputStream)
(import 'java.util.zip.ZipOutputStream)
(import 'java.util.zip.ZipEntry)
You need a way to initialize the stream. This can be done nicely with the -> macro:
(defn zip-stream
"Opens a ZipOutputStream over the given file (as a string)"
[file]
(-> (FileOutputStream. file)
BufferedOutputStream.
ZipOutputStream.))
You need a way to create/close entries in the ZipOutputStream
(defn create-zip-entry
"Create a zip entry with the given name. That will be the name of the file inside the zipped file."
[stream entry-name]
(.putNextEntry stream (ZipEntry. entry-name)))
Finally you need a way to write your content.
(defn write-to-zip
"Writes a string to a zip stream as created by zip-stream"
[stream str]
(.write stream (.getBytes str)))
Putting it all together:
(with-open [stream (zip-stream "coolio.zip")]
(create-zip-entry stream "foo1.txt")
(write-to-zip stream "Hello Foo1")
(.closeEntry stream) ;; don't forget to close entries
(create-zip-entry stream "foo2.txt")
(write-to-zip stream "Hello Foo 2")
(.closeEntry stream))
The result:
I'm making a GET request using clj-http and the response is a zip file. The contents of this zip is always one CSV file. I want to save the CSV file to disk, but I can't figure out how.
If I have the file on disk, (fs/unzip filename destination) from the Raynes/fs library works great, but I can't figure out how I can coerce the response from clj-http into something this can read. If possible, I'd like to unzip the file directly without
The closest I've gotten (if this is even close) gets me to a BufferedInputStream, but I'm lost from there.
(require '[clj-http.client :as client])
(require '[clojure.java.io :as io])
(->
(client/get "http://localhost:8000/blah.zip" {:as :byte-array})
(:body)
(io/input-stream))
You can use the pure java java.util.zip.ZipInputStream or java.util.zip.GZIPInputStream. Depends how the content is zipped. This is the code that saves your file using java.util.zip.GZIPInputStream :
(->
(client/get "http://localhost:8000/blah.zip" {:as :byte-array})
(:body)
(io/input-stream)
(java.util.zip.GZIPInputStream.)
(clojure.java.io/copy (clojure.java.io/file "/path/to/output/file")))
Using java.util.zip.ZipInputStream makes it only a bit more complicated :
(let [stream (->
(client/get "http://localhost:8000/blah.zip" {:as :byte-array})
(:body)
(io/input-stream)
(java.util.zip.ZipInputStream.))]
(.getNextEntry stream)
(clojure.java.io/copy stream (clojure.java.io/file "/path/to/output/file")))
(require '[clj-http.client :as httpc])
(import '[java.io File])
(defn download-unzip [url dir]
(let [saveDir (File. dir)]
(with-open [stream (-> (httpc/get url {:as :stream})
(:body)
(java.util.zip.ZipInputStream.))]
(loop [entry (.getNextEntry stream)]
(if entry
(let [savePath (str dir File/separatorChar (.getName entry))
saveFile (File. savePath)]
(if (.isDirectory entry)
(if-not (.exists saveFile)
(.mkdirs saveFile))
(let [parentDir (File. (.substring savePath 0 (.lastIndexOf savePath (int File/separatorChar))))]
(if-not (.exists parentDir) (.mkdirs parentDir))
(clojure.java.io/copy stream saveFile)))
(recur (.getNextEntry stream))))))))
How do I read a tab-delimited file using Clojure? There may be whitespaces in a line which do not correspond to a tab.
E.g.: transform
some field another-field a third field
into
["some field" "another-field" "a third field"]
You can use the data.csv Contrib library:
;; in your :dependencies
[org.clojure/data.csv "0.1.2"]
;; at the REPL
(require '[clojure.data.csv :as csv])
(csv/read-csv
(java.io.StringReader. "some field\tanother-field\ta third field")
:separator \tab)
;= (["some field" "another-field" "a third field"])
(Use something like (with-open [rdr (clojure.java.io/reader f)] (vec (csv/read-csv rdr :separator \tab))) to read data from the TSV file f.)
If you don't want to do it by hand you could use a CSV library, e.g.:
https://github.com/clojure/data.csv
https://github.com/davidsantiago/clojure-csv
Then you'd be on the save side if your requirements change (e.g. you want to allow spaces in values, the delimiter changes, you want quoting, ...) since you could easily adapt. However, directly splitting single lines works, too:
(require '[clojure.java.io :as io]
'[clojure.string :as string])
(with-open [rd (io/reader (io/file "/path/to/file"))]
(->> (line-seq rd)
(map #(.split ^String % "\t"))
(mapv vec)))
Still, I'd go with a library if I were you.
I'm trying to reach out to the terminal in Clojure to concatenate two binary files together.
So I'm trying to do something like: cat file1 file2 > target
I've started looking at conch but I can't seem to get cat to treat my inputs as file paths rather than strings, e.g.
(def files '["/tmp/file1" "/tmp/file2"])
(defn add-to-target [files target]
(cat {:in files :out (java.io.File. target)}))
(add-to-target files "/tmp/target")
The result written to the /tmp/target file is:
/tmp/file1
/tmp/file2
I'm happy to try other (perhaps more Clojure idiomatic) ways to do this.
Thanks in advance.
Here you go:
(ns user
(:require [clojure.java.io :as io]))
(defn catto [f1 f2 out]
(with-open [o (io/output-stream out)]
(io/copy (io/file f1) o)
(io/copy (io/file f2) o)))
;; in REPL
;; > (catto "station.mov" "super.pdf" "zzz.bin")
Take a look at clojure.java.io docs.
I know there are a lot of related questions, I have read them but still have not gained some fundamental understanding of how to read-process-write. Take the following function for example which uses clojure-csv library to parse a line
(defn take-csv
"Takes file name and reads data."
[fname]
(with-open [file (reader fname)]
(doseq [line (line-seq file)]
(let [record (parse-csv line)]))))
What I would like to obtain is data read into some collection as a result of (def data (take-csv "file.csv")) and later to process it. So basically my question is how do I return record or rather a list of records.
"doseq" is often used for operations with side effect. In your case to create collection of records you can use "map":
(defn take-csv
"Takes file name and reads data."
[fname]
(with-open [file (reader fname)]
(doall (map (comp first csv/parse-csv) (line-seq file)))))
Better parse the whole file at ones to reduce code:
(defn take-csv
"Takes file name and reads data."
[fname]
(with-open [file (reader fname)]
(csv/parse-csv (slurp file))))
You also can use clojure.data.csv instead of clojure-csv.core. Only should rename parse-csv to take-csv in previous function.
(defn put-csv [fname table]
(with-open [file (writer fname)]
(csv/write-csv file table)))
With all the things you can do with .csv files, I suggest using clojure-csv or clojure.data.csv. I mostly use clojure-csv to read in a .csv file.
Here are some code snippets from a utility library I use with most of my Clojure programs.
from util.core
(ns util.core
^{:author "Charles M. Norton",
:doc "util is a Clojure utilities directory"}
(:require [clojure.string :as cstr])
(:import java.util.Date)
(:import java.io.File)
(:use clojure-csv.core))
(defn open-file
"Attempts to open a file and complains if the file is not present."
[file-name]
(let [file-data (try
(slurp file-name)
(catch Exception e (println (.getMessage e))))]
file-data))
(defn ret-csv-data
"Returns a lazy sequence generated by parse-csv.
Uses open-file which will return a nil, if
there is an exception in opening fnam.
parse-csv called on non-nil file, and that
data is returned."
[fnam]
(let [csv-file (open-file fnam)
inter-csv-data (if-not (nil? csv-file)
(parse-csv csv-file)
nil)
csv-data
(vec (filter #(and pos? (count %)
(not (nil? (rest %)))) inter-csv-data))]
(if-not (empty? csv-data)
(pop csv-data)
nil)))
(defn fetch-csv-data
"This function accepts a csv file name, and returns parsed csv data,
or returns nil if file is not present."
[csv-file]
(let [csv-data (ret-csv-data csv-file)]
csv-data))
Once you've read in a .csv file, then what you do with its contents is another matter. Usually, I am taking .csv "reports" from one financial system, like property assessments, and formatting the data to be uploaded into a database of another financial system, like billing.
I will often either zipmap each .csv row so I can extract data by column name (having read in the column names), or even make a sequence of zipmap'ped .csv rows.
Just to add this good answers, here is a full example
First, add clojure-csv into your dependencies
(ns scripts.csvreader
(:require [clojure-csv.core :as csv]
[clojure.java.io :as io]))
(defn take-csv
"Takes file name and reads data."
[fname]
(with-open [file (io/reader fname)]
(-> file
(slurp)
(csv/parse-csv))))
usage
(take-csv "/path/youfile.csv")