[英]Java execute multiple console commands on loaded program
我想从控制台加载程序,然后在其上执行命令。 加载工作正常,但是我怎么能在加载的程序上执行命令而不是每次我想要使用它时都启动它?
例如:./ undomapp command1 command2
但是在Java上,每次我想在其上执行某些操作时都必须使用./randomapp命令,因此程序不会保持加载状态。
不知道你的Java程序或你想执行的应用程序以及命令提供的任何内容,这是一个黑暗的镜头。 此外,省略了所有错误处理。 我正在使用tee来运行该程序,因为它很方便。
public class Command {
private static OutputStream os;
private static OutputStreamWriter osw;
private static Process process;
public static void start(){
try {
ProcessBuilder pb = new ProcessBuilder( "/usr/bin/tee", "x.dat" );
process = pb.start();
os = process.getOutputStream();
osw = new OutputStreamWriter( os );
} catch( Exception e ){
// error handling
} catch( Error e ){
// error handling
}
}
public static void terminate() throws Exception {
process.waitFor();
}
public static void command( String str ) throws Exception {
String cmd = str + System.lineSeparator();
osw.write( cmd, 0, cmd.length() );
osw.flush();
}
我用以下方法测试过:
Command.start();
Command.command( "line 1" );
Thread.sleep( 2000 );
Command.command( "line 2" );
Thread.sleep( 2000 );
Command.command( "line 3" );
Command.terminate();
这些行可以在x.dat上找到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.