All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dongliu.jpackage.util.ProcessUtils Maven / Gradle / Ivy

The newest version!
package net.dongliu.jpackage.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.concurrent.*;

/**
 * Utils for process
 *
 * @author dongliu
 */
public class ProcessUtils {

    private static final ExecutorService executor = Executors.newCachedThreadPool(r -> {
        Thread t = new Thread(r);
        t.setDaemon(true);
        t.setName("process-executor");
        return t;
    });

    public static ProcessResult execute(String... command) {
        ProcessBuilder builder = new ProcessBuilder(command);

        Process process;
        try {
            process = builder.start();

            Future stdout = executor.submit(() -> {
                try (InputStream in = process.getInputStream()) {
                    return new String(in.readAllBytes());
                }
            });
            Future stderr = executor.submit(() -> {
                try (InputStream in = process.getErrorStream()) {
                    return new String(in.readAllBytes());
                }
            });
            process.waitFor(10, TimeUnit.MINUTES);
            return new ProcessResult(process.exitValue(), stdout.get(), stderr.get());
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy