java jshelllink,如何使用jshell运行Java应用程序?

How to run a java application with jshell? It should be able to specify classpath and call java command and pass some arguments like bash does,e.g,

#!/bin/bash

$ARGS=...

$CLASSPATH=...

java -cp $CLASSPATH $ARGS com.example.MyApp

Update:

I think a wrapper of Runtime or Process is required, e.g.,

jshell> private String executeCommand(String command) {

...>

...> StringBuffer output = new StringBuffer();

...>

...> Process p;

...> try {

...> p = Runtime.getRuntime().exec(command);

...> p.waitFor();

...> BufferedReader reader =

...> new BufferedReader(new InputStreamReader(p.getInputStream()));

...>

...> String line = "";

...> while ((line = reader.readLine())!= null) {

...> output.append(line + "\n");

...> }

...>

...> } catch (Exception e) {

...> e.printStackTrace();

...> }

...>

...> return output.toString();

...>

...> }

| Created method executeCommand(String)

jshell> String out =executeCommand("java --version");

out ==> "java 9.0.4\nJava(TM) SE Runtime Environment (bui ... d 9.0.4+11, mixed mode)\n"

jshell> System.out.println(out);

java 9.0.4

Java(TM) SE Runtime Environment (build 9.0.4+11)

Java HotSpot(TM) 64-Bit Server VM (build 9.0.4+11, mixed mode)

解决方案

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")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值