V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
rqxiao
V2EX  ›  程序员

请问 Java Runtime.getRuntime().exec(command) 有没有办法得到执行的结果

  •  
  •   rqxiao · 2020-07-02 17:17:11 +08:00 · 1356 次点击
    这是一个创建于 1633 天前的主题,其中的信息可能已经有所发展或是发生改变。

    比如去 ftp 上下载一个压缩文件,用 Runtime.getRuntime().exec(command)去解压

    得到解压成功的结果后 ,再去读取文件

    有时候 读文件的时候,文件还没有解压完.........

    6 条回复    2020-07-02 17:58:23 +08:00
    lff0305
        1
    lff0305  
       2020-07-02 17:41:45 +08:00
    Process p = Runtime.getRuntime().exec(.....);
    p.waitFor();
    wujieyuan
        2
    wujieyuan  
       2020-07-02 17:44:01 +08:00
    public static CommandResult exec(String cmd) {
    int result = -1;
    BufferedReader successResult = null;
    BufferedReader errorResult = null;
    StringBuilder successMsg = null;
    StringBuilder errorMsg = null;
    try {
    Process process = Runtime.getRuntime().exec(cmd);
    result = process.waitFor();
    successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
    errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    String s;
    successMsg = new StringBuilder();
    while ((s = successResult.readLine()) != null) {
    successMsg.append(s).append("\n");
    }
    errorMsg = new StringBuilder();
    while ((s = errorResult.readLine()) != null) {
    errorMsg.append(s).append("\n");
    }
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    try {
    if (successResult != null)
    successResult.close();
    if (errorResult != null)
    errorResult.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    String success = successMsg == null ? "" : successMsg.toString();
    if (success.endsWith("\n"))
    success = success.substring(0, success.length() - 1);
    String error = errorMsg == null ? "" : errorMsg.toString();
    if (error.endsWith("\n"))
    error = error.substring(0, error.length() - 1);
    return new CommandResult(result, success, error);
    }
    jjianwen68
        3
    jjianwen68  
       2020-07-02 17:46:14 +08:00
    hutool 封装的一些小工具还是很方便的 RuntimeUtil
    DoodleSit
        4
    DoodleSit  
       2020-07-02 17:50:31 +08:00
    ```
    private static Logger logger = LoggerFactory.getLogger(ShellCmd.class.getName());

    private static final String COMMAND_SH = "sh";
    private static final String COMMAND_LINE_END = "\n";
    private static final String COMMAND_EXIT = "exit\n";
    private static ExecutorService pool;

    private static Process process(String command) {
    Runtime rt = Runtime.getRuntime();
    Process p = null;
    try {
    p = rt.exec(command);
    } catch (IOException e) {
    e.printStackTrace();
    p = null;
    }
    return p;
    }

    private static void initPool() {
    if (pool != null) {
    pool.shutdownNow();
    pool = null;
    }
    pool = Executors.newCachedThreadPool();
    }

    public static String exec(String command) {
    if (RegexHelper.isEmpty(command)) return "nil";
    int runningStatus = -1;
    try {
    initPool();
    Process process = process(COMMAND_SH);
    try {
    DataOutputStream dos = new DataOutputStream(process.getOutputStream());
    dos.write(command.getBytes());
    dos.writeBytes(COMMAND_LINE_END);
    dos.flush();
    dos.writeBytes(COMMAND_EXIT);
    dos.flush();
    dos.close();
    InputStream err = process.getErrorStream();
    InputStream normal = process.getInputStream();
    List<Future<String>> futureList = new ArrayList<>();
    futureList.add(pool.submit(new StreamReaderWorker(normal, StreamType.NORMAL)));
    futureList.add(pool.submit(new StreamReaderWorker(err, StreamType.ERROR)));
    runningStatus = process.waitFor();
    for (Future<String> future : futureList) {
    try {
    String str = future.get();
    logger.warn(str);
    } catch (ExecutionException e) {
    e.printStackTrace();
    }
    }
    process.destroy();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }

    } catch (IOException e) {
    e.printStackTrace();
    }
    return "" + runningStatus;
    }
    ```

    很早之前写的,用着没啥问题
    DoodleSit
        5
    DoodleSit  
       2020-07-02 17:52:26 +08:00
    public interface StreamType {
    static int NORMAL = 1;
    static int ERROR = 2;
    }

    public class StreamReaderWorker implements StreamType, Callable<String> {

    private int type;
    private InputStream is;

    public StreamReaderWorker(InputStream is, int type) {
    this.is = is;
    this.type = type;
    }


    @Override
    public String call() throws Exception {
    if (is == null) return null;
    BufferedReader br = null;
    InputStreamReader isr = null;
    boolean isReadSth = false;
    try {
    isr = new InputStreamReader(is);
    br = new BufferedReader(isr);
    String line = null;
    StringBuffer stringBuffer = new StringBuffer();
    while ((line = br.readLine()) != null) {
    isReadSth = true;
    stringBuffer.append(line);
    }
    return stringBuffer.toString();
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    try {
    if (br != null) br.close();
    if (isr != null) isr.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    if (is != null) {
    try {
    is.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    return "";
    }


    }
    misaka19000
        6
    misaka19000  
       2020-07-02 17:58:23 +08:00
    搜索引擎能搜到的对象为什么还要问一遍呢?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2726 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 09:16 · PVG 17:16 · LAX 01:16 · JFK 04:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.