3
votes

I want to use a changeable file in clojure-project. (Manjaro Linux & Leiningen 2.8.0 on Java 1.8.0_144 OpenJDK 64-Bit Server VM)

So, I tried ... ($ echo resources/temp.txt => Hello )

(ns test.core
  (:require [clojure.java.io :refer [writer input-stream]]
            [clojure.java.io :as io])
  (:gen-class))

(str (io/resource ""))
(defn -main
  []
 (with-open [r (input-stream (io/resource "temp.txt"))]
    (loop [c (.read r)] 
      (if (not= c -1)
        (do 
          (print (char c)) 
          (recur (.read r))))))
  (with-open [r (writer (.getFile (io/resource "temp.txt")))]
    (.write r "See you!"))
  )

and project.clj is here ...

(defproject test "0.1.0-SNAPSHOT"
   :description "FIXME: write description"
   :url "http://example.com/FIXME"
   :license {:name "Eclipse Public License"
             :url "http://www.eclipse.org/legal/epl-v10.html"}
   :dependencies [[org.clojure/clojure "1.8.0"]]
   :main test.core)

This program can run in lein-run

$ lein run
Hello
$ 

But this cannot run in lein-uberjar -> java -jar test-0.1.0-SNAPSHOT-standalone.jar

$ lein uberjar
$ java -jar test-0.1.0-SNAPSHOT-standalone.jar
Exception in thread "main" java.io.FileNotFoundException: /home/***/Documents/test/target/test-0.1.0-SNAPSHOT-standalone.jar!/temp.txt (
No such file or directory)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at clojure.java.io$fn__9522.invokeStatic(io.clj:230)
at clojure.java.io$fn__9522.invoke(io.clj:230)
at clojure.java.io$fn__9459$G__9428__9466.invoke(io.clj:69)
at clojure.java.io$fn__9526.invokeStatic(io.clj:242)
at clojure.java.io$fn__9526.invoke(io.clj:240)
at clojure.java.io$fn__9459$G__9428__9466.invoke(io.clj:69)
at clojure.java.io$fn__9534.invokeStatic(io.clj:261)
at clojure.java.io$fn__9534.invoke(io.clj:259)
at clojure.java.io$fn__9459$G__9428__9466.invoke(io.clj:69)
at clojure.java.io$fn__9496.invokeStatic(io.clj:166)
at clojure.java.io$fn__9496.invoke(io.clj:166)
at clojure.java.io$fn__9472$G__9424__9479.invoke(io.clj:69)
at clojure.java.io$writer.invokeStatic(io.clj:119)
at clojure.java.io$writer.doInvoke(io.clj:104)
at clojure.lang.RestFn.invoke(RestFn.java:410)
at test.core$_main.invokeStatic(core.clj:15)
at test.core$_main.invoke(core.clj:7)
at clojure.lang.AFn.applyToHelper(AFn.java:152)
at clojure.lang.AFn.applyTo(AFn.java:144)
at test.core.main(Unknown Source)

How do I get correct path to it? Thank you.

1
But I was able to find the file in that jar-file with sudo jar -xvf *-standalone.jar temp.txtTakuya Ebata

1 Answers

1
votes

One problem is that .getFile doesn't work in a jar file, because you're reading from a zip file, not a directory structure on the file system. Also, it's not recommended to change files inside a jar file (I'm not sure it's even possible). Also see Reading a resource file from within jar.