Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/377.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用参数封装命令的更好方法_Java_Encapsulation - Fatal编程技术网

Java 使用参数封装命令的更好方法

Java 使用参数封装命令的更好方法,java,encapsulation,Java,Encapsulation,我有一个impl类,它有几个方法,它们基本上都使用runtime.exec和不同的参数列表调用脚本,例如 public String doExport(String ruleIds, String fileName) throws Exception{ StringBuffer cmd = new StringBuffer(); cmd.append(SOME_SCRIPT + " -a export "); cmd.append(" -f " )

我有一个impl类,它有几个方法,它们基本上都使用runtime.exec和不同的参数列表调用脚本,例如

public String doExport(String ruleIds, String fileName) throws Exception{
        StringBuffer cmd = new StringBuffer();
        cmd.append(SOME_SCRIPT + " -a export ");
        cmd.append(" -f " );
        cmd.append(fileName);
        cmd.append(" -r " );
        cmd.append(ruleIds);
        cmd.append(" 2>/dev/null");
        return execCmd(cmd.toString());
    }

    public String doImport(String fileName, String user, String iface) throws Exception {
        StringBuffer cmd = new StringBuffer();
        cmd.append(SOME_SCRIPT + " -a import ");
        cmd.append(" -f " );
        cmd.append(fileName);
        cmd.append(" -m " );
        cmd.append("user");
        cmd.append(" -u " );
        cmd.append(user);
        cmd.append(" -I " );
        cmd.append(iface);
        return execCmd(cmd.toString());
    } 
public String setRulesMode(String mode) throws Exception {
        String cmd = SOME_SCRIPT + " -a ";
        return execCmd(cmd.toString());
    }
有没有更好的办法?比如封装命令和参数或者更通用的方法?我尝试使用enum,但发现在有静态/常量参数列表的情况下,enum更适合使用,因此,我想寻找更好的交互方式。

我会创建“CommandBuilder”,它包装了
ProcessBuilder
,并且能够编写和运行命令行

请注意,将标准输出重定向到文件的尝试将不起作用。重定向是一种shell功能。您可以通过shell运行命令(例如,unix上的
/bin/sh your command>your file
,或windows上的
cmd-c your command>your file

更好的方法是使用java中的
Process.setOutputStream()
。它是可移植的,易于调试和维护。这可能是您的
CommandBuilder的功能

编辑

以下是有关CommandBuilder结构的一些提示

public class CommandBuilder {
    public void setPrefix(); // e.g. cmd or /bin/sh But some kind of automatic logic should be implemented too, i.e. cmd for windows, /bin/sh for unix
    public void setCommand(); // for example ping
    public void addArgument(String value);  // e.g. myhost
    public void setInputStream(InputStream in);
    public void setOutputStream(OutputStream in);

    // add appropriate getters.

    public Process exec();
    public int execAndWait(); // returns process status
}

谢谢Alex,我想构建类似commandBuilder的东西,它将封装命令,但要为不同命令的不同参数寻找通用实现……您能详细说明一下commandBuilder的外观吗?或者您指的是使用apache中的commandBuilder吗?请看一下我编写的示例谢谢你,科林,我不知道那是什么,但请你找找看。。