rishi kant rishi kant - 3 months ago 13
Java Question

Why print function is not printing when invoked with java -jar?

I'm learning clojure with leiningen. I have written a simple code to test lein & java -jar commands. Here is my project.clj file:

$ cat project.clj
(defproject hello "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 ^:skip-aot hello.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all}})


Here is my source code:

$ cat src/hello/core.clj
(ns hello.core
(:gen-class))

(defn -main
[& args]
(print "Hello, World!"))


When I run this code with lein, It work fine. It's shown here

$ lein run
Hello, World!$


When I tried to run java -jar, It didn't work

$ lein uberjar
Compiling hello.core
Created /home/rishi/hello/target/uberjar/hello-0.1.0-SNAPSHOT.jar
Created /home/rishi/hello/target/uberjar/hello-0.1.0-SNAPSHOT-standalone.jar

$ java -jar target/uberjar/hello-0.1.0-SNAPSHOT-standalone.jar


I didn't understand, why I didn't get required output with java -jar?

If I replace print with println in source file, I got required output with both lein run & java -jar.

Answer

Your process output is buffered. print does not flush the output. Most of the time your output stream will be set up to automatically flush on newlines, which is why the println displays. If you need to flush without a newline, you can call the (flush) function.