java调用cmd命令

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class Cmd3Util {
    public static Map.Entry<List<String>,List<String>> execute(String[] commands) {
        log.info("commands is `{}`",String.join(" ",commands));
        Map.Entry<List<String>,List<String>> entry = null;
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(commands);
            Process process = processBuilder.start();
            ExecutorService service = Executors.newFixedThreadPool(2);
            CompletableFuture<List<String>> okFuture = CompletableFuture.supplyAsync(() -> handler(process.getInputStream()),service);
            CompletableFuture<List<String>> errFuture = CompletableFuture.supplyAsync(() -> handler(process.getErrorStream()),service);
            try {
                int exitCode = process.waitFor();
                log.info("exitCode is {}",exitCode);
            }catch (Exception ex) {
                ex.printStackTrace();
            }finally {
                CompletableFuture.allOf(okFuture,errFuture).join();
                List<String> okList = okFuture.get();
                List<String> errList = errFuture.get();
                entry = new AbstractMap.SimpleEntry<>(okList,errList);
                service.shutdown();
                process.destroy();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return entry;
    }

    private static List<String> handler(InputStream inputStream) {
        try(InputStream is = inputStream) {
            return IOUtils.readLines(is, StandardCharsets.UTF_8);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String[] commands = new String[3];
        commands[0] = "yt-dlp";
        commands[1] = "-F";
        commands[2] = "https://www.youtube.com/watch?v=0qs8aAsufjQ";
        Map.Entry<List<String>,List<String>> entry = execute(commands);
        List<String> okList = entry.getKey();
        List<String> errList = entry.getValue();
        okList.forEach(log::info);
        log.info("----------------------");
        errList.forEach(log::info);
    }
}

posted @ 2023-06-25 13:50  小小爬虫  阅读(69)  评论(0编辑  收藏  举报