Skip to main content
replaced http://stackoverflow.com/ with https://stackoverflow.com/
Source Link
URL Rewriter Bot
URL Rewriter Bot

Here is a linklink to another question with a very detailed answer on how to do this correctly in an async way with threads. This is the only way to not block your main thread and hang your GUI.

Here is a link to another question with a very detailed answer on how to do this correctly in an async way with threads. This is the only way to not block your main thread and hang your GUI.

Here is a link to another question with a very detailed answer on how to do this correctly in an async way with threads. This is the only way to not block your main thread and hang your GUI.

Source Link
user177800
user177800

Here is a link to another question with a very detailed answer on how to do this correctly in an async way with threads. This is the only way to not block your main thread and hang your GUI.

private class ProcessResultReader extends Thread
{
    final InputStream is;
    final String type;
    final StringBuilder sb;

    ProcessResultReader(@Nonnull final InputStream is, @Nonnull String type)
    {
        this.is = is;
        this.type = type;
        this.sb = new StringBuilder();
    }

    public void run()
    {
        try
        {
            final InputStreamReader isr = new InputStreamReader(is);
            final BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null)
            {
                this.sb.append(line).append("\n");
            }
        }
        catch (final IOException ioe)
        {
            System.err.println(ioe.getMessage());
            throw new RuntimeException(ioe);
        }
    }

    @Override
    public String toString()
    {
        return this.sb.toString();
    }
}

then you use the above class like so

try
{
    final Process p = Runtime.getRuntime().exec(String.format("cmd /c %s", query));
    final ProcessResultReader stderr = new ProcessResultReader(p.getErrorStream(), "STDERR");
    final ProcessResultReader stdout = new ProcessResultReader(p.getInputStream(), "STDOUT");
    stderr.start();
    stdout.start();
    final int exitValue = p.waitFor();
    if (exitValue == 0)
    {
        System.out.print(stdout.toString());
    }
    else
    {
        System.err.print(stderr.toString());
    }
}
catch (final IOException e)
{
    throw new RuntimeException(e);
}
catch (final InterruptedException e)
{
    throw new RuntimeException(e);
}