Java Runtime.getRuntime() 非法参数异常

标签 java runtime-error

我在让 .getruntime.exec() 正常工作时遇到了一些问题。这是处理该部分的代码:

while (line != null)
{
  String name = line;
  String commandFull = commandFirst + name + commandLast;

  String[] fullCommand = new String[] {commandFirst, name, commandLast};
  for(int i=0;i<3;i++)
  {
    System.out.print(fullCommand[i]);
  }
  Runtime runner = Runtime.getRuntime();
  Process p = runner.exec(fullCommand);

  outFile.println(fullCommand);

  line = inFile.readLine();
}

它打印出它应该看起来的命令。当我在这里运行程序时,输出是:

adfind -b dc=stuff,dc=com -f "cn=user" |find "displayName" >> fullList.txt
Exception in thread "main" java.lang.IllegalArgumentException
        at java.lang.ProcessImpl.<init>(Unknown Source)
        at java.lang.ProcessImpl.start(Unknown Source)
        at java.lang.ProcessBuilder.start(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at lookup.main(lookup.java:41)

最佳答案

您正试图在没有 shell 的情况下执行 shell 命令。

也就是说,您正在尝试执行 shell 会解释的内容(特别是管道 '|' 和附加 '>>')。要解决这个问题,让 Java 执行一个 shell 实例并将整个命令传递给 shell。这将如何工作取决于平台。

例如在 Linux 中:

String fullCommand = {"/bin/sh", "-c", "find -b dc=stuff,dc=com -f \"cn=user\" |find \"displayName\" >> fullList.txt"};

或者在 Windows 中:

String fullCommand = {"cmd.exe", "/c", "find -b dc=stuff,dc=com -f \"cn=user\" |find \"displayName\" >> fullList.txt"};

关于Java Runtime.getRuntime() 非法参数异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1121871/

相关文章:

spring-mvc - 错误页面在tomcat中正常工作,但在weblogic中工作不正常

java.lang.NoClassDefFoundError : com/google/gwt/json/client/JSONParser at runtime when trying to parse json 错误

java - 如何在 JPA 中设置默认架构

java - JPA 客户端-服务器复制/同步框架?

java - 如何从 jsonarray 读取值?

java - 使用 BorderLayout 和现有的 JScrollPane 将 Swing 元素添加到 JFrame

java - Path.getParent() 为空

javascript - meteor/javascript 函数在另一个文件中时不起作用

c - 在 C 语言中添加矩阵代码 帮助!我不知道出了什么问题

ios - 根据设备的大小更改 UIImageViews 的位置