使用`java.lang.ProcessBuilder`执行shell命令

时间:2016-01-25 08:45:22

标签: java coldfusion railo

我在CFML中编写了以下小脚本执行shell命令,我的问题是输出,只要输出单行即可,如果是多行我只得到第一行,我试过了在脚本上执行while循环(在代码上注释)但不起作用,Java抛出内存错误java.lang.OutOfMemoryError: Java heap space。我该怎么办?

<cfscript>
  str = ":>exec uname";
  exec_init=str.split(":>exec ");
  exec=exec_init[2].split(" ");
  p = createObject("java","java.lang.ProcessBuilder").init(exec).start();
  i = createObject("java","java.io.InputStreamReader").init(p.getInputStream());
  br = createObject("java","java.io.BufferedReader").init(i);
  line=br.readLine();
  //while (isDefined("line")) {
   //writeoutput(line);
  //}
  br.close();
  i.close();
</cfscript>

<cfdump var="#line#">

输出:

Linux

如果我发出像

这样的命令

ls

多行输出我得到了。

README.TXT

代替:

README.TXT VERSION.txt _-Railo-Getting-Started-_.html bin etc jre lib license-eplv10-aslv20.html modules notice.html resources start start.d start.ini start.jar stop webapps

1 个答案:

答案 0 :(得分:2)

发现问题,我需要在循环中再次添加line = br.readLine();。工作代码:

<cfscript>
  str = ":>exec ls -al";
  exec_init=str.split(":>exec ");
  exec=exec_init[2].split(" ");
  p = createObject("java","java.lang.ProcessBuilder").init(exec).start();
  i = createObject("java","java.io.InputStreamReader").init(p.getInputStream());
  br = createObject("java","java.io.BufferedReader").init(i);
  line = br.readLine();
  while (isDefined("line")) {
   writeoutput(line);
   line = br.readLine();
  }
  br.close();
  i.close();
</cfscript>