Get Command Prompt Output to String In Java

前端 未结 3 1446
春和景丽
春和景丽 2020-12-16 23:19

I need a java method that will read command prompt output and store it into a String to be read into Java.

This is what I have so far but isn\'t working right.

3条回答
  •  余生分开走
    2020-12-17 00:02

    First you need a non-blocking way to read from Standard.out and Standard.err

    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 need to tie this class into the respective InputStream and OutputStreamobjects.

        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);
        }
    

    This is pretty much the boiler plate I use when I need to Runtime.exec() anything in Java.

    A more advanced way would be to use FutureTask and Callable or at least Runnable rather than directly extending Thread which isn't the best practice.

    NOTE:

    The @Nonnull annotations are in the JSR305 library. If you are using Maven, and you are using Maven aren't you, just add this dependency to your pom.xml.

    
      com.google.code.findbugs
      jsr305
      1.3.9
    
    

提交回复
热议问题