2013-08-19 47 views
4

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

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); 
      } 
    } 
} 
+2

此代码正尝试写入progam正在运行的当前目录中名为'Documents'的目录。该目录是否存在? – andy256

+0

@ andy256是的,它的确如此。 –

回答

1

附加运算符>>意味着被解释为命令shell的一部分。使用

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

谢谢:)这个效果很好。 –

2

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

也试试InputStreamError Stream,并完整阅读。看看是否有任何有用的反馈。

除此之外,请尝试和y256在评论中建议的内容。确保Documents目录存在于程序的执行目录中。