how to run a command at terminal from java program?

前端 未结 6 2157
孤城傲影
孤城傲影 2020-11-29 03:14

I need to run a command at terminal in Fedora 16 from a JAVA program. I tried using

Runtime.getRuntime().exec(\"xterm\"); 

but this just op

6条回答
  •  一向
    一向 (楼主)
    2020-11-29 03:59

    You don't actually need to run a command from an xterm session, you can run it directly:

    String[] arguments = new String[] {"/path/to/executable", "arg0", "arg1", "etc"};
    Process proc = new ProcessBuilder(arguments).start();
    

    If the process responds interactively to the input stream, and you want to inject values, then do what you did before:

    OutputStream out = proc.getOutputStream();  
    out.write("command\n");  
    out.flush();
    

    Don't forget the '\n' at the end though as most apps will use it to identify the end of a single command's input.

提交回复
热议问题