How to run a java application with jshell?

谁说胖子不能爱 提交于 2019-12-01 09:11:39

For Running any application in jshell first set the classpath to the jshell at the starting.

Example:

jshell -class-path /Users/sree/Desktop/libs/jettison-1.0.1.jar 

Then import the class into the environment running

import org.codehaus.jettison.json.JSONObject;

This will import the required class into the environment.

Now run the required application. In my case, I entered

String myString = new JSONObject().put("JSON", "Hello, World!").toString()

And got back the output

myString ==> "{\"JSON\":\"Hello, World!\"}"

answering the question for passing command line arguments. you have to initiate the class with all the values.

Test instance = new Test("data","data1")

Your code is broken, as you are waiting for the command’s completion first and only afterwards reading the pipe. If the command produces more output than the pipe can buffer, the command will get blocked and never complete, as no-one is reading the pipe at this point.

In a perfect world, you would just use

new ProcessBuilder(your command and args).inheritIO().start().waitFor()

as in a normal Java application. Unfortunately, jshell changes the standard file descriptors in a way that this doesn't work (at least in the Windows version I tested).

You can use

void run(String... arg) throws IOException, InterruptedException {
  Path tmp = Files.createTempFile("run", ".tmp");
  try {
    new ProcessBuilder(arg).redirectErrorStream(true).redirectOutput(tmp.toFile())
      .start().waitFor();
    Files.lines(tmp, java.nio.charset.Charset.defaultCharset())
      .forEach(System.out::println);
  }
  finally { Files.delete(tmp); }
}

and call it like, e.g.

run("java", "-version")

or

run("java", "-d", "java.base")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!