【问题标题】:Java - Command Execution in RuntimeJava - 运行时的命令执行
【发布时间】:2013-08-19 23:07:53
【问题描述】:

我尝试了一个在运行时执行 Linux 命令的简单程序。但是下面的程序编译并运行没有任何错误,但是文本文件没有按预期创建。这个程序有什么问题吗?

import java.io.*;
class ExecuteJava
{
    public static void main(String args[])
    {
            String historycmd = "cat ~/.bash_history >> Documents/history.txt";
            try
            {
                    Runtime runtime = Runtime.getRuntime();
                    Process proc = runtime.exec(historycmd);
            }
            catch(Exception e)
            {
                    System.out.println(e);
            }
    }
}

【问题讨论】:

  • 此代码正在尝试写入程序运行所在的当前目录中名为Documents 的目录。该目录是否存在?
  • @andy256 是的,确实如此。

标签: java runtime.exec


【解决方案1】:

尝试访问Process 提供的一些功能。我将从exitValue 开始。通常-1 表示出现问题,而0 表示没有发生特别糟糕的事情。

也可以尝试InputStreamError Stream,并完整阅读它们。看看有没有对你有用的反馈。

除此之外,试试 andy256 在 cmets 中的建议。确保程序的执行目录中存在Documents目录。

【讨论】:

    【解决方案2】:

    附加运算符>> 被解释为命令外壳的一部分。使用

    String[] historycmd = 
               { "bash", "-c", "cat ~/.bash_history >> Documents/history.txt"};
    

    【讨论】:

      猜你喜欢
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多