JAVA調用UNIX命令有點問題,請高手指點
我在UNXI系統上用下面的命令運行:
java -jar Run.jar /usr/bin ls>/123.txt
沒有報錯,在根目錄下也有123.txt這個文件
可是里面沒有東西
請問是為什么
以下附源程序:
import java.io.File; // is java code
import java.io.InputStream;
 
public class RunSystemCommand {
    public static void main(String args[]){
try{
if(args[0].equals("/h"))
{
System.out.println("the work directory of your bin folder and the command you want to run!");
System.exit(0);
}
String s = null;
// system command to run
String cmd = args[1];
// set the working directory for the OS command processor
File workDir = new File(args[0]);

Process p = Runtime.getRuntime().exec(cmd, null, workDir);
InputStream pis = p.getInputStream();
while( pis.read() != -1 ); // added, as otherwise the ls hangs.
p.waitFor();
System.out.println("This is the end of the command!");
}
catch(Exception e){
System.out.println("Error:");
e.printStackTrace();
}
    }
}

解决方案 »

  1.   

    情况可能是这样的:
    Runtime.getRuntime().exec 启动的是一个另外的进程(不管是不是当前进程的子进程),这个新的进程的标准输出并没有被连接到当前进程的标准输出来。这不,Process类有一个方法getOutputStream,估计这个方法就是获得新进程的标准输出的吧。所以,如果您想让ls命令的结果输出到/123.txt文件的话,自己动手,把新进程的标准输出的东西写进那个文件吧。