代码之家  ›  专栏  ›  技术社区  ›  StealthRT

来自接口的Java回调

  •  0
  • StealthRT  · 技术社区  · 5 年前

    嘿,我读过一些stackoverflow的文章,是关于从回调接口获取值的。从这些例子中并没有得到很好的理解。

    主要代码:

    public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {
    CmdExecResult cmd = null;       
        List<String> cmdCommand = Arrays.asList(
            "lscm login -r https://XXXXXX:0000/ccm -n XXXX.XXXX -u [name here] -P V_g8#D5gee@",
        );
    
        List<String> cmdDir = Arrays.asList(
            scmDir,
            ...
        );
    
        int x = 0;
    
        for (String state : cmdCommand) {
            //Wait until function is complete before moving to another one
            CompletableFuture<String> cf = CompletableFuture.completedFuture(execCmdSync(cmdDir.get(x) + state, ));
            System.out.println(cf.get());
            x++;
    
            if (!cf.isDone()) {
                break;
            }
        }
    

    界面:

    public interface CmdExecResult{
        void onComplete(boolean success, int exitVal, String error, String output, String originalCmd);
    }
    

    以及从main调用的函数:

    public static String execCmdSync(String cmd, CmdExecResult callback) throws java.io.IOException, InterruptedException {
        Runtime rt              = Runtime.getRuntime();
        Process proc            = rt.exec(cmd);     
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
        StringBuffer stdOut     = new StringBuffer();
        StringBuffer errOut     = new StringBuffer();
        String s                = null;
    
        // Read the output from the command:        
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
            stdOut.append(s);
        }
    
        // Read any errors from the attempted command:      
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
            errOut.append(s);
        }
    
        if (callback == null) {
            return stdInput.toString();
        }
    
        int exitVal = proc.waitFor();
        callback.onComplete(exitVal == 0, exitVal, errOut.toString(), stdOut.toString(), cmd);
    
        return stdInput.toString();
    }
    

    我怎样才能拔出钥匙 来自 主要功能 查阅 (可完成的未来)?

    0 回复  |  直到 5 年前