Publish Your Article Here

Program: How to run operating system specific command and read its output?


Below example shows how to run operating specific command and read its output. ProcessBuilder class can helps you to run any commands.

package com.java2novice.processbuilder;


public class MyOsCommandRun {

	public static void main(String a[]){
		InputStream is = null;
		ByteArrayOutputStream baos = null;
		ProcessBuilder pb = new ProcessBuilder("ls", "-l");
		try {
			Process prs = pb.start();
			is = prs.getInputStream();
			byte[] b = new byte[1024];
			int size = 0;
			baos = new ByteArrayOutputStream();
			while((size = != -1){
				baos.write(b, 0, size);
			System.out.println(new String(baos.toByteArray()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
		} finally{
			try {
				if(is != null) is.close();
				if(baos != null) baos.close();
			} catch (Exception ex){}

total 0
drwxrwxrwx  4 root  846622648  136 Aug 25 17:14 bin
drwxrwxrwx  3 root  846622648  102 Jul  5 21:22 resources
drwxrwxrwx  3 root  846622648  102 Mar 26 21:57 src
<< Previous Program | Next Program >>

List Of All ProcessBuilder Class Sample Programs:

  1. How to invoke other applicatons in java?
  2. How to run operating system specific command and read its output?
  3. How to get process environment variables in java at runtime?
  4. How to run ProcessBuilder with list of commands?
Knowledge Centre
StringBuffer Vs StringBuilder
The only difference between StringBuffer and StringBuilder is StringBuffer is thread-safe, that is StringBuffer is synchronized.
Famous Quotations
Good judgment comes from experience, and experience comes from bad judgment.
-- Barry LePatner

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.