【问题标题】:Java command prompt commands throw "No such File or Directory"Java 命令提示符命令抛出“没有这样的文件或目录”
【发布时间】:2019-07-22 11:10:41
【问题描述】:

我目前正在开发一个应该执行一些控制台命令的程序。

我的代码如下所示:

  private String executeCommands(String[] commands)
  {
    String result = "";
    try
    {
      ProcessBuilder pb = new ProcessBuilder();
      String s = null;
      Charset charset = Charset.forName("IBM850");
      BufferedReader stdInput;
      Process proc;
      for (String command : commands)
      {
        System.out.println("Ausfuehrung von: " + command);
        pb.command(command);
        proc = pb.start();
        stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream(), charset));
        while ((s = stdInput.readLine()) != null)
        {
          result += s;
        }
        System.out.println();
      }
    }
    catch (Exception ex)
    {
      result = ex.getMessage();
    }
    return result;
  }
  private void userLogIn(IUserInteraction userInteraction)
  {
    String[] command = { "svn auth --show-passwords" };
    String result = executeCommands(command);
    System.out.println(result);
  }

输出是“无法运行程序“svn auth --show-passwords”:错误=2,没有这样的文件或目录”,但是当我在控制台中手动输入命令时,它可以工作。我做错了什么?

提前致谢!

【问题讨论】:

  • 在您的代码中,您是否从正确的目录(与手动运行时相同的目录)运行命令?
  • 是的,都来自 /home/user
  • 你的环境变量列表中有svn吗?尝试在java代码中打印环境变量并检查是否存在。
  • @GurmeetGulati 当我运行 java.util.Map env = System.getenv(); env 地图包含空值

标签: java linux console


【解决方案1】:

经过一些尝试,我找到了一个可行的解决方案

String result
String line;
      Process process = Runtime.getRuntime().exec(command);
      Reader r = new InputStreamReader(process.getInputStream());
      BufferedReader in = new BufferedReader(r);
      while ((line = in.readLine()) != null)
        result += line;
      in.close();

【讨论】:

    【解决方案2】:

    svn 如果没有将环境变量传送到您的应用程序,则对 jvm 没有任何意义。

    尝试使用完整路径执行命令:

    String[] command = { "/bin/dir1/dir2/svn auth --show-passwords" };
    

    如果你不知道程序在哪里,使用下面的命令来弄清楚:

    which svn
    

    【讨论】:

    • which svn 的结果是 /usr/bin/svn。我将此添加到命令中,但结果相同
    猜你喜欢
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多